Reshaping Pandas Data frames with Melt & Pivot

import pandas as pd

df = pd.DataFrame(data = {
    'Day' : ['MON', 'TUE', 'WED', 'THU', 'FRI'], 
    'Google' : [1129,1132,1134,1152,1152], 
    'Apple' : [191,192,190,190,188] 
})

reshaped_df = df.melt(id_vars=['Day'], var_name='Company', value_name='Closing Price')

reshaped_df.head()

Unmelt/Reverse Melt/Pivot

original_df = reshaped_df.pivot(index='Day', columns='Company')['Closing Price'].reset_index()
original_df.columns.name = None

original_df.head()

Оригинал статьи: https://www.freblogg.com/pandas-melt-pivot

Print Friendly, PDF & Email

Добавить комментарий