[英]Can I create column where each row is a running list in a Pandas data frame using groupby?
[英]How to create a Pandas Groupby object where each column has a filter on the original data?
我正在尝试使用 Pandas 复制以下 SQL,但它比我预期的要复杂得多:
SELECT
id
, count(*)
, count(case when some_condition = True then 1 end)
, count(case when some_other_condition = False then 1 end)
FROM table
GROUP BY id
我唯一能想到的是这样的:
grouped = df.groupby('id')
df_total = grouped.count()
df_some_condition = grouped.filter(...).count()
df_some_other_condition = grouped.filter(...).count()
df_total.join(df_some_condition, on='id').join(df_some_other_condition, on='id')
我只是惊讶于我无法使用 groupby().count() 创建过滤列,而且我必须创建 3 个单独的数据框然后加入它们。 有没有更简单的方法来做到这一点,我忽略了?
注意:这里的语法可能不完全正确,只是快速写了一些东西来说明我的问题。
df = pd.DataFrame({'id': [1, 1, 2, 2, 3, 3, 4],
'val1': [0.0, 48.0, 4.0, 20.0, 24.0, 25.0, 0.0],
'val2': [0.0, 0.0, 1.0, 40.0, 22.0, 7.0, 13.0]})
df
id val1 val2
0 1 0.0 0.0
1 1 48.0 0.0
2 2 4.0 1.0
3 2 20.0 40.0
4 3 24.0 22.0
5 3 25.0 7.0
6 4 0.0 13.0
如何重新创建选择
df.assign(result1 = np.where(df['val1']<25, 1,0),
result2 = np.where(df['val2'] > 4,1,0)).groupby('id').agg(count=('id','size'),
res1_sum=('result1',sum),
res2_sum=('result2',sum))
输出
count res1_sum res2_sum
id
1 2 1 0
2 2 2 1
3 2 1 2
4 1 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.