作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的设置如下
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 成为索引,这不是我想要的(我认为)。也许有更好的方法涉及 pivot
、pivot_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/
我是一名优秀的程序员,十分优秀!