如何将数据框架从长格式转换为宽格式,并按计数

时间:2015-12-13 21:15:14

标签: python pandas

我的设置如下

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

1 个答案:

答案 0 :(得分:2)

您可以使用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
相关问题