【问题标题】:pandas - updating a dataframe column with value of another column with if conditionpandas - 使用 if 条件使用另一列的值更新数据框列
【发布时间】:2021-09-06 12:53:02
【问题描述】:

如果ColumnC中有“0”和字符串“pandas”,我想用平均值更新ColumnA [我存储在columnB中]

df['ColumnA'] = df.apply(lambda x: x['ColumnB'] if (x['ColumnA']==0 & x['ColumnC']=='pandas') else x['ColumnA'], axis=1)

我收到了这个错误

unsupported operand type(s) for &: 'int' and 'str'

请告诉我如何解决它

【问题讨论】:

  • 使用and 而不是&(x['ColumnA']==0 and x['ColumnC']=='pandas') & 适用于熊猫系列,但由于您通过行应用x['ColumnA'] 是python 标量,因此您不能使用@ 987654328@.

标签: python pandas dataframe


【解决方案1】:

在您的条件周围加上括号,并在 cmets 中指出,使用 and 代替 & 进行标量比较,例如

((x['ColumnA'] == 0) and (x['ColumnC'] == 'pandas'))

参见this question on order of operations - 位运算符& 优先于布尔运算符==

也就是说,您应该考虑使用矢量化操作:

df['ColumnA'] = df['ColumnB'].where(
    ((df['ColumnA'] == 0) & (df['ColumnC'] == 'pandas')),
    df['ColumnA'],
)

这几乎在所有情况下都比 df.apply 快。

【讨论】:

    【解决方案2】:

    使用and 代替& 并在== 测试周围加上括号:

    df['ColumnA'] = df.apply(lambda x: x['ColumnB'] if (x['ColumnA']==0) and (x['ColumnC']=='pandas') else x['ColumnA'], axis=1)
    

    【讨论】:

      猜你喜欢
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 2021-11-02
      • 1970-01-01
      • 2019-06-24
      • 2022-01-07
      • 2020-05-28
      相关资源
      最近更新 更多