gpt4 book ai didi

python - 按两列分组,求和、计数并在单独的列中显示输出值( Pandas )

转载 作者:行者123 更新时间:2023-12-04 11:25:43 26 4
gpt4 key购买 nike

我有一个数据集 df,我想对两列进行分组,取另一列的总和和计数,并在单独的列中列出字符串
数据

id  date    pwr type
aa q321 10 hey
aa q321 1 hello
aa q425 20 hi
aa q425 20 no
bb q122 2 ok
bb q122 1 cool
bb q422 5 sure
bb q422 5 sure
bb q422 5 ok
欲购
id  date    pwr count   type
aa q321 11 2 hey
hello
aa q425 40 2 hi
no
bb q122 3 2 ok
cool
bb q422 15 3 sure
sure
ok
g = df.groupby(['id', 'date'])['pwr'].sum().reset_index()
g['count'] = g['id'].map(df['id'].value_counts())
这工作正常,除了,我不知道如何显示列“类型”的字符串输出
任何建议表示赞赏。

最佳答案

您可以使用 .GroupBy.transform() 设置列的值 pwrcount .然后.set_index()在除 type 之外的 4 列上获得类似于所需输出的布局:

df['pwr'] = df.groupby(['id', 'date'])['pwr'].transform('sum')
df['count'] = df.groupby(['id', 'date'])['pwr'].transform('count')

df.set_index(['id', 'date', 'pwr', 'count'])
输出:
                    type
id date pwr count
aa q321 11 2 hey
2 hello
q425 40 2 hi
2 no
bb q122 3 2 ok
2 cool
q422 15 3 sure
3 sure
3 ok

关于python - 按两列分组,求和、计数并在单独的列中显示输出值( Pandas ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68487888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com