pbPassingBI
/

How would you reshape wide data into long?

intermediate
Answer

pd.melt, giving the columns to keep as id_vars and the columns to unpivot as value_vars.

pd.melt(df, id_vars=['product'], value_vars=['jan','feb','mar'],
        var_name='month', value_name='revenue')

It matters because groupby, seaborn's hue, and most plotting expect long form. Data arriving from spreadsheets is almost always wide, so melt is usually the first step after loading.

pivot_table goes the other way when you need a report-shaped output at the end.

Related