【发布时间】:2018-05-05 22:17:12
【问题描述】:
【问题讨论】:
标签: python pandas dataframe pivot reshape
【问题讨论】:
标签: python pandas dataframe pivot reshape
使用 cumcount 创建附加密钥,然后我们执行 pivot ,来自 jpp 的数据
df.assign(key=df.groupby('Col1').cumcount()).pivot('key','Col1','Col2')
Out[29]:
Col1 A B C
key
0 1.0 4.0 6.0
1 2.0 5.0 7.0
2 3.0 NaN 8.0
【讨论】:
一种方法是在从键列中的唯一值派生的系列上使用pandas.concat。
这是一个最小的例子。
import pandas as pd
df = pd.DataFrame({'Col1': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'],
'Col2': [1, 2, 3, 4, 5, 6, 7, 8]})
res = pd.concat({k: df.loc[df['Col1']==k, 'Col2'].reset_index(drop=True)
for k in df['Col1'].unique()}, axis=1)
print(res)
A B C
0 1 4.0 6
1 2 5.0 7
2 3 NaN 8
【讨论】: