我有一个类似于以下内容的DataFrame
调用df
:(其中所有值都是字符串):
id type variable
---------------------------------------------
A a item_1
A a item_2
A a item_3
A b item_4
A b item_5
A b item_6
A c item_7
A c item_8
A c item_9
我想将其转换为:
type a |b |c
id
------------------------------------------------------------------------------
A item_1|item_2|item_3 | item_4 | item_5 |item_6| item_7 |item_8 | item_9
基本上,我想将列type
并variable
安排在多层列中。这显然是一个快照,但基本上我对每个9个不同的值id
在df
我尝试了以下代码:
df.pivot(index = 'id', columns = 'type', values = 'variable')
但是出现以下错误:
ValueError: Index contains duplicate entries, cannot reshape
我敢肯定有一个相当简单的解决方案,我只是没有想到!我将不胜感激任何帮助。谢谢
cumcount
在此处创建一个帮助键(通过使用)以消除错误Index contains duplicate
df.assign(helpkey=df.groupby('type').cumcount()).set_index(['id','type','helpkey']).variable.unstack([-2,-1])
Out[138]:
type a b c \
helpkey 0 1 2 0 1 2 0 1
id
A item_1 item_2 item_3 item_4 item_5 item_6 item_7 item_8
type
helpkey 2
id
A item_9
我们也可以使用 crosstab
pd.crosstab(index=df.id,columns=[df.type,df.groupby('type').cumcount()],values=df.variable,aggfunc='sum')
Out[144]:
type a b c
col_1 0 1 2 0 1 2 0 1 2
id
A item_1 item_2 item_3 item_4 item_5 item_6 item_7 item_8 item_9
或pivot_table
:
df.assign(helpkey=df.groupby('type').cumcount()).pivot_table(index='id',columns=['type','helpkey'],values='variable', aggfunc='sum')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句