2017-04-02 43 views
0

我有一个需求,我需要将数据帧列的行转换为列,但是我在GROUPBY之后遇到问题。 下面是一组3个用户,其类型可以在type1到type6之间。Python - 将行转换为列后,为非匹配行填充0

user_id1 type4 
user_id1 type6 
user_id1 type1 
user_id1 type2 
user_id1 type1 
user_id1 type6 
user_id2 type1 
user_id2 type2 
user_id2 type2 
user_id2 type1 
user_id2 type3 
user_id2 type4 
user_id2 type5 
user_id2 type6 
user_id2 type2 
user_id2 type6 
user_id3 type1 
user_id3 type2 
user_id3 type3 
user_id3 type2 

我期待的输出 -

user_id type1 type2 type3 type4 type5 type6 
user_id1 2 1  0  1  0  2 
user_id2 2 3  1  1  1  2 
user_id3 1 2  1  0  0  0 

我试图做的类型GROUPBY,得到了count.But不知道如何转换为列特别是缺少类型应该是人口稠密与0.

非常感谢您的时间。

+0

显示代码你尝试过什么? –

+0

[pandas pivoting a dataframe,duplicate rows]可能重复(http://stackoverflow.com/questions/11400181/pandas-pivoting-a-dataframe-duplicate-rows) – philshem

回答

0

你需要使用的是来自熊猫的pivot_table。你可以指定你需要的行和列,fill_value说明你想用空值和aggfunc len计数做什么。

我不知道你的DataSeries是什么样子,但你需要某事像这样:

pd.pivot_table(data, index='user_id', columns='type', aggfunc=len, fill_value=0)