【问题标题】:How to fixed 'ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().' when & is used如何修复'ValueError:DataFrame 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。何时使用 &
【发布时间】:2019-03-02 06:00:39
【问题描述】:

我想根据多列条件重新分配值,但出现了ValueError。我使用& 而不是and,这通常是解决此类错误的答案。我的目标和代码如下:

ValueError: The truth value of a DataFrame is ambiguous. 
Use a.empty, a.bool(), a.item(), a.any() or a.all().

如果CountryBorn == CanadaYearsInCanada == None,我想重新编码YearsInCanada == Age

df
Age    CountryBorn    YearsInCanada
87     NaN            77      
67     Canada         67
29     US             7
26     US             10
22     US             12
35     Canada         NaN
45     Canada         NaN

expected output
Age    CountryBorn    YearsInCanada
87     NaN            77      
67     Canada         67
29     US             7
26     US             10
22     US             12
35     Canada         35
45     Canada         45

我的以下代码显示ValueError

    if df.loc[(df['YearsInCanada'] == None) & (df['CountryBorn'] == 'Canada')]:
        df['YearsInCanada'] == df['Age']

    else:
        df['YearsInCanada'] == df['YearsInCanada']

谢谢

【问题讨论】:

  • 为什么最后一个值是 35?不应该是45吗?
  • @anky_91 感谢指出,错字。

标签: python pandas valueerror


【解决方案1】:

使用np.where()的解决方案:

df.YearsInCanada=np.where((df['YearsInCanada'].isna()) & (df['CountryBorn'] == 'Canada'),\
                      df.YearsInCanada.fillna(df.Age),df.YearsInCanada)
print(df)

   Age CountryBorn  YearsInCanada
0   87         NaN           77.0
1   67      Canada           67.0
2   29          US            7.0
3   26          US           10.0
4   22          US           12.0
5   35      Canada           35.0
6   45      Canada           45.0

【讨论】:

    【解决方案2】:
    df.loc[(df['YearsInCanada'] == None) & (df['CountryBorn'] == 'Canada')]
    

    这会返回一个(衍生的)数据框。 if 需要布尔表达式。

    如果您尝试进行矢量化分配,则必须将其编码为 Pandas 动作 + 过滤器,而不是 Python if

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-28
      • 2021-07-31
      • 2021-08-31
      • 2016-12-01
      • 2021-03-21
      • 2022-12-29
      • 2019-01-24
      • 2021-08-06
      相关资源
      最近更新 更多