python - 在 groupby 之后过滤行并应用函数

标签 python pandas pandas-groupby

我正在使用 python 和 pandas 来处理一些数据。 我的数据如下所示:

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                         'foo', 'bar'],
                   'B' : [1, 2, 3, 4, 5, 6],
                   'C' : [True, False, True, True, False, True]})
print(df)

     A  B      C
0  foo  1   True
1  bar  2  False
2  foo  3   True
3  bar  4   True
4  foo  5  False
5  bar  6   True

我想做的事:

  1. 按“A”分组
  2. 按组选择值 B,其中 C == True
  3. 计算此选择的平均值
  4. 创建新列“D”来存储这些值

所以结果是:

    A   B   C       D
0   foo 1   True    2
1   bar 2   False   5
2   foo 3   True    2
3   bar 4   True    5
4   foo 5   False   2
5   bar 6   True    5

我尝试了一些 groupby、过滤器和转换的组合,但我无法成功使其工作。 我想象解决方案接近以下内容

df.groupby(["A"])[df.loc[df["C"] == True, "B"]].transform("mean")

df.groupby(["A"]).filter(lambda x: x["D"] == True)["B"].transform("mean")

但是这些语法都不起作用。

感谢您帮助我和一般人,

最佳答案

使用Series.map对于过滤行的平均值,应省略==True:

df['D'] = df['A'].map(df.loc[df.C, 'B'].groupby(df["A"]).mean())
print(df)

     A  B      C  D
0  foo  1   True  2
1  bar  2  False  5
2  foo  3   True  2
3  bar  4   True  5
4  foo  5  False  2
5  bar  6   True  5

关于python - 在 groupby 之后过滤行并应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60706977/

相关文章:

python - Pandas 按层次多重索引分组,不丢失其他索引

python - 将 pandas groupby 值转换为 numpy 数组

python - 在 Python 中生成 CSR

python - 我可以精确控制cythonize生成的.c文件的位置吗?

python - 如何将值从 1 列分配给另一列并在 Pandas 中发出警告

python - 使用 Pandas 进行数据分组

python - 如何将字符串转换为int? dtype ("O")-值错误: invalid literal for int() with base 10: ''

python - 是否值得用 cython 重写我的代码?

python - 类型错误 "Bad input argument to theano function"

python - Pandas 数据框中不可散列的类型错误