2017-05-31 60 views
1

我有这样的数据框头,我想做一个pivot_table。使用熊猫做出pivot_table,但发生错误

user_id  item_id cate_id action_type action_date 
0 11482147 492681 1_11 view   15 
1 12070750 457406 1_14 deep_view  15 
2 12431632 527476 1_1  view   15 
3 13397746 531771 1_6  deep_view  15 
4 13794253 510089 1_27 deep_view  15 

有20000+ user_id和37个cate_id,5个action_type。 我想做一个这样的pivot_table,我用excel来完成它。表中的值应该是每个cate_id的每个user_id的value_count。 pivot_table 我试过下面的代码。

user_cate_table = pd.pivot_table(user_cate_table2,index = ['user_id','cate_id'],columns=np.unique(train['action_type']),values='action_type',aggfunc=np.count_nonzero,fill_value=0) 

我收到了这条消息。

ValueError: Grouper and axis must be same length 

dataframe user_cate_table2的头部。

user_id  item_id cate_id action_type 
0 11482147 492681 1_11 1.0 
1 12070750 457406 1_14 2.0 
2 12431632 527476 1_1  1.0 
3 13397746 531771 1_6  2.0 
4 13794253 510089 1_27 2.0 
5 14378544 535335 1_6  2.0 
6 1705634  535202 1_10 1.0 
7 6943823  478183 1_3  2.0 
8 5902475  524378 1_6  1.0 
+0

什么意思'np.unique(火车[ 'ACTION_TYPE'])'?另一个数据框的列的唯一值? – jezrael

+0

是的,原始数据帧名为train.That是我在顶部显示 –

+0

因此,有2个数据帧,需要'pivot_table'与他们?你可以添加第二个数据帧的样本和期望的输出吗?谢谢。 – jezrael

回答

1

我想你需要groupby + size + unstack

df1 = df.groupby(['user_id','cate_id', 'action_type']).size().unstack(fill_value=0) 
print (df1) 
action_type  deep_view view 
user_id cate_id     
11482147 1_11    0  1 
12070750 1_14    1  0 
12431632 1_1    0  1 
13397746 1_6    1  0 
13794253 1_27    1  0 

另一种解决方案与pivot_table

df1 = df.pivot_table(index=['user_id','cate_id'], 
        columns='action_type', 
        values='item_id', 
        aggfunc=len, 
        fill_value=0) 
print (df1) 
action_type  deep_view view 
user_id cate_id     
11482147 1_11    0  1 
12070750 1_14    1  0 
12431632 1_1    0  1 
13397746 1_6    1  0 
13794253 1_27    1  0 
+0

我再次和@jezrael一样得到同样的答案,我在编译我的代码时发布了 –

+0

@MaartenFabré - 谢谢。我检查你的答案,这有点不同,但我不知道如果OP想要我的解决方案或你的东西。 – jezrael

+0

我认为'.size'使用'.np.count_nonzero',所以下降到相同的,我没有使用'fill_value'。其余的是可比的 –

0

你不需要使用pivot_table。您可以使用groupbyunstack

df.groupby(['user_id', 'cate_id', 'action_type'])['action_date'].agg(np.count_nonzero).unstack('action_type') 

pivot_table作品太多,但不是你误会了columns=参数

pd.pivot_table(df,index = ['user_id','cate_id'],columns=['action_type'],aggfunc=np.count_nonzero,fill_value=0)