Python Pandas:为特定列值的每个实例创建新列

时间:2017-08-30 18:57:05

标签: python pandas dataframe

我有一个像这样的数据框

----------------
RecID| A  |B
----------------
1    |Dog | x 
2    |Dog | y 
3    |Dog | z
4    |Cat | a 
5    |Cat | b 

并且想要知道是否还有改变它以便它是这样的:

-----------------------------
RecID| A |B_1|B_2|B_3|
-----------------------------
1    |Dog| x | y | z |
2    |Cat| a | b | NA| 

基本上创建B的每个可能值的新列,按A的特定值分组,如果需要,用NA填充。

2 个答案:

答案 0 :(得分:3)

一种方法是

foo.mydomain.com

或者,

In [294]: (df.groupby('A', sort=False).B.apply(list)
             .apply(pd.Series).add_prefix('B_').reset_index())
Out[294]:
     A B_0 B_1  B_2
0  Dog   x   y    z
1  Cat   a   b  NaN

答案 1 :(得分:0)

set_indexgroupbycumcount

一起使用
df.set_index(
    ['A', df.groupby('A').cumcount() + 1]
).B.unstack().add_prefix('B_').reset_index()

     A B_1 B_2   B_3
0  Cat   a   b  None
1  Dog   x   y     z
相关问题