【发布时间】:2016-06-30 15:48:41
【问题描述】:
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 first 或 ' '.join 但返回 CSV 而不是相应行上的值。
【问题讨论】:
标签: python pandas text grouping