Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在特定值上聚合数据帧?_Python_Pandas_Pandas Groupby_Pandas Apply - Fatal编程技术网

Python 如何在特定值上聚合数据帧?

Python 如何在特定值上聚合数据帧?,python,pandas,pandas-groupby,pandas-apply,Python,Pandas,Pandas Groupby,Pandas Apply,我有一个像这样的pandasdataframedf,比如 ID activity date 1 A 4 1 B 8 1 A 12 1 C 12 2 B 9 2 A 10 3 A 3 3 D 4 我想返回一个表,在一个精确的列表中计算一些活动的发生次数,比如说l=[a,B],那么 ID activity(count)_A activity(count)_B 1 2

我有一个像这样的
pandas
dataframe
df
,比如

ID activity date
1  A        4
1  B        8
1  A        12
1  C        12
2  B        9
2  A        10
3  A        3
3  D        4
我想返回一个表,在一个精确的列表中计算一些
活动的发生次数,比如说
l=[a,B]
,那么

ID activity(count)_A  activity(count)_B
1  2                  1
2  1                  2
3  1                  0
这就是我需要的

最快的方法是什么?理想情况下,无
for
循环

谢谢

编辑:我知道有
pivot
功能来做这种工作。但是在我的例子中,我的
活动
类型比我在列表
l
中真正需要计算的要多得多。使用
pivot
是否仍然是最佳选择?

您可以使用作为第一步,然后使用pivot-最快的应该是,然后是最后,最好使用真实数据测试每个解决方案:

df2 = (df[df['activity'].isin(['A','B'])]
         .groupby(['ID','activity'])
         .size()
         .unstack(fill_value=0)
         .add_prefix('activity(count)_')
         .reset_index()
         .rename_axis(None, axis=1))

print (df2)
   ID  activity(count)_A  activity(count)_B
0   1                  2                  1
1   2                  1                  1
2   3                  1                  0
或:

或:

我相信
df.groupby('activity').size().reset_index(name='count')

应该按照您的期望来做。

只需通过
计数器进行聚合
并使用
pd.DataFrame
默认构造函数即可

from collections import Counter

agg_= df.groupby(df.index).ID.agg(Counter).tolist()
ndf = pd.DataFrame(agg_)

    A   B   C   D
0   2   1.0 1.0 NaN
1   1   1.0 NaN NaN
2   1   NaN NaN 1.0
如果你有
l=['A','B']
,只需过滤

ndf[l]

    A   B   
0   2   1.0 
1   1   1.0 
2   1   NaN
from collections import Counter

agg_= df.groupby(df.index).ID.agg(Counter).tolist()
ndf = pd.DataFrame(agg_)

    A   B   C   D
0   2   1.0 1.0 NaN
1   1   1.0 NaN NaN
2   1   NaN NaN 1.0
ndf[l]

    A   B   
0   2   1.0 
1   1   1.0 
2   1   NaN