How can I "unpivot" specific columns from a pandas DataFrame? How can I "unpivot" specific columns from a pandas DataFrame? python python

How can I "unpivot" specific columns from a pandas DataFrame?


This can be done with pd.melt():

# value_name is 'value' by default, but setting it here to make it clearpd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')

Result:

  farm  fruit  year  value0    A  apple  2014     101    B  apple  2014     122    A   pear  2014      63    B   pear  2014      84    A  apple  2015     115    B  apple  2015     136    A   pear  2015      77    B   pear  2015      9[8 rows x 4 columns]

I'm not sure how common "melt" is as the name for this kind of operation, but that's what it's called in R's reshape2 package, which probably inspired the name here.