【问题标题】:Loop return error that the true value of the series is ambiguous序列的真值不明确的循环返回错误
【发布时间】:2019-07-08 08:51:05
【问题描述】:

我有以下数据集:

我想告诉熊猫:

如果报表编号小于30,他需要创建一个等于的新变量

df_bei_index[col]*0.05 + df_bei_index['PDI_Average']*0.95.

如果报表编号大于等于30,他需要创建一个新的变量,等于

df_bei_index[col]

我写了以下代码:

for col in col_list:
    if df_bei_index['Report No'] <= 29:
        df_bei_index[col+'_final'] = df_bei_index[col]*0.05 + df_bei_index['PDI_Average']*0.95
    else:
        df_bei_index[col+'_final'] = df_bei_index[col]

但是我得到了这个错误


ValueError Traceback(最近一次调用最后一次) 在 () 10 col_list 中的 col 为 11: ---> 12 如果 df_bei_index['Report No']

~\Anaconda3\lib\site-packages\pandas\core\generic.py 在 nonzero(self) 1574 raise ValueError("{0} 的真值不明确。" 1575 "使用 a.empty, a.bool()、a.item()、a.any() 或 a.all()。” -> 1576 .format(self.class.name)) 1577 1578 bool = 非零

ValueError:Series 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python pandas loops conditional-statements


    【解决方案1】:

    df_bei_index['Report No'] &lt;= 29 这样的表达式具有Series(bool) 类型,因此您不能在if 语句中使用它,但您可以将它用作.loc 中数据帧的索引:

    import pandas as pd
    
    data = {'a': list(range(20)), 'b': list(range(6,26))}
    df = pd.DataFrame(data = data)
    
    condition1 = df.a <= 10
    condition2 = df.a > 10
    df.loc[condition1, 'a_1'] = df.loc[condition1]['a'] * 2
    df.loc[condition2, 'a_1'] = df.loc[condition2]['a'] * 5
    

    【讨论】:

      【解决方案2】:

      检查这个答案: Python Use if function: ValueError:Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

      你可能想使用 np.where:

      for col in col_list:
              df_bei_index[col+'_final'] = np.where(df_bei_index['Report No'] <=29, df_bei_index[col]*0.05 + df_bei_index['PDI_Average']*0.95, df_bei_index[col])
      

      我假设您从“col_list”列表中排除了“国家”列

      【讨论】:

        猜你喜欢
        • 2021-06-26
        • 1970-01-01
        • 2014-10-28
        • 2018-01-11
        • 2016-07-11
        • 1970-01-01
        • 2020-08-11
        • 1970-01-01
        • 2021-08-13
        相关资源
        最近更新 更多