df = pd.DataFrame({'Col1': ['label1', 'label1', 'label2', 'label2',
'label3', 'label3', 'label4'],
'Col2': ['a', 'd', 'b', 'e', 'c', 'f', 'q']}, columns=['Col1', 'Col2'])
看起来像这样
Col1 Col2
0 label1 a
1 label1 d
2 label2 b
3 label2 e
4 label3 c
5 label3 f
6 label4 q
对于Col1中的唯一值,我想将列的唯一值转换为列.从某种意义上说,我试图将Col1值“取消堆叠”为列标题,行值将是Col2中的值.我的关键主要问题是我不是在计算任何数字数据 – 它都是文本 – 而我只是试图重塑结构.
这是期望的结果:
label1 label2 label3 label4
0 a b c q
1 d e f NaN
我试过了:stack,unstack,pd.melt,pivot_table,pivot.
这几乎让我在那里,但并不完全,并且似乎不是很简洁:
df.groupby('Col1').apply(lambda x: x['Col2'].values).to_frame().T
Col1 label1 label2 label3 label4
0 [a, d] [b, e] [c, f] [q]
This question shows how to do it with a pivot table ..但我的情况下的数字索引不是我关心的事情.
This question shows how to also do it with a pivot table ..首先使用aggfunc或’.join但返回CSV而不是各行的值.
解决方法:
您可以使用cumcount
为新索引创建列,然后使用聚合连接创建pivot_table
:
df['g'] = df.groupby('Col1')['Col1'].cumcount()
print (df.pivot_table(index='g', columns='Col1', values='Col2', aggfunc=''.join))
Col1 label1 label2 label3 label4
g
0 a b c q
1 d e f None
df['g'] = df.groupby('Col1')['Col1'].cumcount()
print (df.pivot(index='g', columns='Col1', values='Col2'))
Col1 label1 label2 label3 label4
g
0 a b c q
1 d e f None
要么:
print (pd.pivot(index=df.groupby('Col1')['Col1'].cumcount(),
columns=df['Col1'],
values=df['Col2']))
Col1 label1 label2 label3 label4
0 a b c q
1 d e f None
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。