Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using column name as a new attribute in pandas

I have the following data structure

Date         Agric  Food 
01/01/1990    1.3   0.9  
01/02/1990    1.2   0.9 

I would like to covert it into the format

Date        Sector  Beta
01/01/1990  Agric   1.3
01/02/1990  Agric   1.2
01/01/1990  Food    0.9
01/02/1990  Food    0.9

while I am sure I can do this in a complicated way, is there a way of doing this in a few line of code?

like image 365
Lost1 Avatar asked Dec 08 '22 17:12

Lost1


1 Answers

Using pd.DataFrame.melt

df.melt('Date', var_name='Sector', value_name='Beta')

         Date Sector  Beta
0  01/01/1990  Agric   1.3
1  01/02/1990  Agric   1.2
2  01/01/1990   Food   0.9
3  01/02/1990   Food   0.9
like image 149
piRSquared Avatar answered Dec 10 '22 05:12

piRSquared