简体   繁体   中英

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

I have the following dataframe:

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'}})

I would like to reshape it like this:

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

How can I do it?

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

gets very close to what I was looking for, but I'd rather do without the first column Variable , if at all possible.

You can try renaming the axis()

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

additionally if you want to reset the index

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}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM