Home > database >  Wide dataframe and longer dataframe transfer
Wide dataframe and longer dataframe transfer

Time:08-08

In pandas, how can I transfer a wide dataframe to a longer dataframe? (ori_df to new_df as in the image.)

On the contrast, how can I transfer new_df to ori_df?

import pandas as pd
ori_df=pd.DataFrame()
ori_df=pd.DataFrame([['a','1'],['w:','z'],['t','6'],['f:','z'],['a','2']],
                    columns=['type','value'])

Enter image description here

CodePudding user response:

Try:

pd.melt(ori_df,id_vars='type',var_name='item',value_name='amount')

or

(ori_df.set_index('type')
.stack()
.sort_index(level=-1,ascending=False)
.rename_axis(['type','item'])
.reset_index(name = 'amount'))
  • Related