如何将此 pandas 数据框从高表示转换为宽表示,删除一列

How to convert this pandas dataframe from a tall to a wide representation, dropping a column

我有以下数据框:

df = pd.DataFrame({'Variable':    {0: 'Abs', 1: 'rho0', 2: 'cp', 3: 'K0'},
                   'Value':       {0: 0.585, 1: 8220.000, 2: 435.000, 3: 11.400},
                   'Description': {0: 'foo', 1: 'foo', 2: 'foo', 3: 'foo'}})

我想像这样重塑它:

df2 = pd.DataFrame({'Abs':  {0: 0.585},
                    'rho0': {0: 8220.000},
                    'cp':   {0: 435.000},
                    'K0':   {0: 11.400}})

我该怎么做?

df3 = df.pivot_table(columns='Variable', values='Value')
print(df3)
Variable    Abs    K0     cp    rho0
Value     0.585  11.4  435.0  8220.0

非常接近我要找的内容,但如果可能的话,我宁愿没有第一列 Variable

您可以尝试重命名轴()

df3 = df.pivot_table(values='Value', columns='Variable').rename_axis(None, axis=1) 

另外如果你想重置索引

df3 = df.pivot_table( columns='Variable').rename_axis(None, axis=1).reset_index().drop('index',axis=1)
df3.to_dict()
# Output 
           {'Abs': {0: 0.585}, 
           'K0': {0: 11.4}, 
           'cp': {0: 435.0}, 
           'rho0': {0: 8220.0}}