import pandas as pd
import numpy as np
df=pd.DataFrame(np.array([['M',1, 1, 2, 3],
['F', 2, 4, 5, 6], ['M', 3, 7, 8, 9]]),columns=['SEX','AGE','A','B','C'])
dfm=pd.melt(df,id_vars=('SEX','AGE'),value_vars=list(df.columns[2:]),
var_name='LOCATION',value_name='DEATHS')
Based on the code provided i can create a basic table and melt the tables from df to dfm using the 'AGE' and 'SEX' as id variables.
Is there a simple way of reverting this table back to its original format? Going from dfm > df assuming i do not have df.
many thanks
The pivot_table method should allow you to return to the original dataframe
# Change data types from object integer
dfm[['AGE', 'DEATHS']] = dfm[['AGE', 'DEATHS']].astype(int)
# Pivot dataframe to "undo melt"
reshaped = dfm.pivot_table(index=['SEX', 'AGE'],columns=['LOCATION'],
values='DEATHS')
# Reset index to flatten dataframe
reshaped.reset_index(inplace=True)
# Change column name attribute to blank
reshaped.columns.rename('',inplace=True)
SEX AGE A B C
0 F 2 4 5 6
1 M 1 1 2 3
2 M 3 7 8 9
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.