gpt4 book ai didi

python - 如何将 DataFrame 从长格式转换为宽格式,按计数聚合列的值

转载 作者:行者123 更新时间:2023-12-01 04:16:27 31 4
gpt4 key购买 nike

我的设置如下

import numpy as np
import pandas as pd

df = pd.DataFrame({'user_id':[1, 1, 1, 2, 3, 3], 'action':['b', 'b', 'c', 'a', 'c', 'd']})
df

action user_id
0 b 1
1 b 1
2 c 1
3 a 2
4 c 3
5 d 3

从中生成数据帧的最佳方法是什么,其中每个唯一的user_id有一行,每个唯一的操作有一列,列值是每个 user_id 的每个操作的计数?

我已经尝试过

df.groupby(['user_id', 'action']).size().unstack('action')

action a b c d
user_id
1 NaN 2 1 NaN
2 1 NaN NaN NaN
3 NaN NaN 1 1

这很接近,但这似乎使 user_id 成为索引,这不是我想要的(我认为)。也许有更好的方法涉及 pivotpivot_table 甚至 get_dummies

最佳答案

您可以使用pd.crosstab :

In [37]: pd.crosstab(index=[df['user_id']], columns=[df['action']])
Out[37]:
action a b c d
user_id
1 0 2 1 0
2 1 0 0 0
3 0 0 1 1

user_id作为索引对我来说似乎合适,但如果您想删除user_id,您可以使用reset_index:

In [39]: pd.crosstab(index=[df['user_id']], columns=[df['action']]).reset_index(drop=True)
Out[39]:
action a b c d
0 0 2 1 0
1 1 0 0 0
2 0 0 1 1

关于python - 如何将 DataFrame 从长格式转换为宽格式,按计数聚合列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256440/

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