【发布时间】:2020-06-24 12:33:57
【问题描述】:
我有以下数据框:
df = pd.DataFrame({
'cluster': ['A','B','C','A','B','C','D','D'],
'profit': [-1.0,1.5,1,0.5,3.0,-2,-1, -2]
})
在输出到另一个数据帧之前,我正在执行一系列 groupby 操作,其中大部分我必须工作。
df['cluster_total_profit'] = df.groupby(['cluster'])['profit'].transform('sum')
df['cluster_mean_profit'] = df.groupby(['cluster'])['profit'].transform('mean')
df['occurances'] = df.groupby(['cluster'])['profit'].transform('count')
df['std'] = df.groupby(['cluster'])['profit'].transform('std')
clusters = df[['cluster','cluster_total_profit', 'cluster_mean_profit', 'occurances', 'std']].drop_duplicates().reset_index(drop=True)
输出如下:
cluster cluster_total_profit cluster_mean_profit occurances std
0 A -0.5 -0.25 2 1.06066
1 B 4.5 2.25 2 1.06066
2 C -1.0 -0.50 2 2.12132
3 D -3.0 -1.50 2 0.707107
我尝试进行的最后一个转换是计算每个组中盈利事件的数量,并用此类事件的数量填充 df。输出可以收集在上表中,如下所示:
cluster cluster_total_profit cluster_mean_profit occurances std profitable_events
0 A -0.5 -0.25 2 1.06066 1
1 B 4.5 2.25 2 1.06066 2
2 C -1.0 -0.50 2 2.12132 1
3 D -3.0 -1.50 2 0.707107 0
我查看了here 和here,但我无法将这些示例转换为我的确切用例。这是我的代码:
df['profitable_events'] = df.cluster.map(df.groupby(['cluster']).filter(lambda x: x[x['profit'] > 0.0].count()))
clusters = df[['cluster','cluster_total_profit', 'cluster_mean_profit', 'occurances', 'std', 'profitable_events']].drop_duplicates().reset_index(drop=True)
和:
df['profitable_events'] = df.groupby(['cluster']).filter(lambda x: x[x['profit'] > 0.0]).transform('count')
两者都抛出错误“TypeError: filter function returned a Series, but expected a scalar bool”
我也试过了:
df['profitable_events'] = df.cluster.map(df.groupby(['cluster']).filter(lambda x: len(x[x['profit'] > 0.0].index)))
其中错误:“TypeError:过滤器函数返回一个 int,但期望一个标量 bool”
我确定有一个快速修复,但不确定它是什么?
在此先感谢
【问题讨论】:
-
你为什么用
transform然后drop_duplicates?不就是df.groupby('cluster').agg(['sum','mean','count','std'])吗? -
啊,这真的很有用——但它并不能完全回答这个问题。我正在寻找一种方法来计算利润> 0 的组中的行数。如果我理解正确,此方法将对组中的每一行而不是过滤后的组进行求和、标准、均值、计数?
标签: python pandas filter pandas-groupby