Python 熊猫:将两列重塑为一行

Python 熊猫:将两列重塑为一行,python,pandas,pivot,Python,Pandas,Pivot,我想将熊猫数据框从两列重塑为一行: import numpy as np import pandas as pd df_a = pd.DataFrame({ 'Type': ['A', 'B', 'C', 'D', 'E'], 'Values':[2,4,7,9,3]}) df_a Type Values 0 A 2 1 B 4 2 C 7 3 D 9 4 E 3 df_b = df_a.pivot(columns='Type', values=

我想将熊猫数据框从两列重塑为一行:

import numpy as np
import pandas as pd
df_a = pd.DataFrame({ 'Type': ['A', 'B', 'C', 'D', 'E'], 'Values':[2,4,7,9,3]})
df_a

   Type Values
0   A   2
1   B   4
2   C   7
3   D   9
4   E   3

df_b = df_a.pivot(columns='Type', values='Values')
df_b
这就给了我:

Type A       B       C       D      E
0   2.0     NaN     NaN     NaN     NaN
1   NaN     4.0     NaN     NaN     NaN
2   NaN     NaN     7.0     NaN     NaN
3   NaN     NaN     NaN     9.0     NaN
4   NaN     NaN     NaN     NaN     3.0
当我想把它压缩成这样一行:

Type A       B       C       D      E
0   2.0     4.0     7.0     9.0     3.0

我相信您不需要
pivot
,最好只使用
DataFrame
构造函数:

df_b = pd.DataFrame([df_a['Values'].values], columns=df_a['Type'].values)
print (df_b)
   A  B  C  D  E
0  2  4  7  9  3
或通过
T
进行转置:

df_b = df_a.set_index('Type').T.rename({'Values':0})
print (df_b)
Type  A  B  C  D  E
0     2  4  7  9  3
另一种方式:

df_a['col'] = 0
df_a.set_index(['col','Type'])['Values'].unstack().reset_index().drop('col', axis=1)

Type    A   B   C   D   E
  0     2   4   7   9   3
我们可以修理你的DFU b

df_b.ffill().iloc[[-1],:]
Out[360]: 
Type    A    B    C    D    E
4     2.0  4.0  7.0  9.0  3.0
或者我们

df_a.assign(key=[0]*len(df_a)).pivot(columns='Type', values='Values',index='key')
Out[366]: 
Type  A  B  C  D  E
key                
0     2  4  7  9  3

谢谢,我以为会有一个简单的解决办法,但事实确实如此。