Wide dataframe and longer dataframe transfer

Question:

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

Asked By: anderwyang

||

Answers:

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'))
Answered By: rhug123
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.