【问题标题】:Pandas groupby and apply custom function comparing two columns to alter another columnPandas groupby 并应用自定义函数比较两列以更改另一列
【发布时间】:2020-05-04 01:25:21
【问题描述】:

我有一个需要按id 分组的数据框,然后在这些组中,比较列A 和B 以更改列C。

这是我的代码:

def alter_C(row):
    if row['A'].shift(1) == row['B'] :
           row['C'] = 'new_value'
           return row

df = df.groupby(id).apply(alter_C)

我得到错误:

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

你能帮忙吗?

【问题讨论】:

  • 这里不需要groupby,检查np.where
  • 编辑了我的帖子,我需要一个分组依据,因为我正在比较这些组中的连续行,感谢您的回复

标签: python pandas pandas-groupby


【解决方案1】:

在groupby 之后使用apply 时,函数的输入将是一个数据帧。所以你的函数中的row 不是单行。您可以通过运行type(row) 来检查这一点,这将为您提供<class 'pandas.core.frame.DataFrame'>。

因此,在更改 C 列时,我们需要将 row 视为数据框。可以这样做:

def alter_C(df_group):
    df_group.loc[df_group['A'].shift(1) == df_group['B'], 'C'] = 'new_value'
    return df_group

df = df.groupby('id').apply(alter_C)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    相关资源
    最近更新 更多