有两个这样的 Pandas 数据框:
Key Value
A 2
A 6
B 7
A 1
B 3
B 4
A 2
我怎样才能以这样的方式 reshape :
A B
2 7
6 3
1 4
2 NaN
最佳答案
您可以使用 groupby
与 apply
用于创建新 index
值(value)观:
df = df.groupby('Key').Value.apply(lambda x: pd.Series(x.values)).unstack(0)
print (df)
Key A B
0 2 7
1 6 3
2 1 4
3 2 0
另一个解决方案
pivot
并创建新 index
值来自 cumcount
:df = pd.pivot(index = df.groupby('Key').cumcount(), columns=df['Key'], values=df['Value'])
print (df)
Key A B
0 2 7
1 6 3
2 1 4
3 2 0
df1 = df.groupby('Key').Value.apply(lambda x: pd.Series(x.values)).unstack(0)
print (df1)
Key A B
0 2.0 7.0
1 6.0 3.0
2 1.0 4.0
3 2.0 NaN
df2 = pd.pivot(index = df.groupby('Key').cumcount(), columns=df['Key'], values=df['Value'])
print (df2)
Key A B
0 2.0 7.0
1 6.0 3.0
2 1.0 4.0
3 2.0 NaN
关于python-2.7 - 将 Pandas 数据框的行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055940/