Using column name as 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 hide it in 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

although I'm sure I can do it in a complicated way, is there a way to do this in a few lines of code?

+4
source share
3 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
+5
source

Use set_indexand stack:

df.set_index('Date').rename_axis('Sector',axis=1).stack()\
  .reset_index(name='Beta')

Conclusion:

         Date Sector  Beta
0  01/01/1990  Agric   1.3
1  01/01/1990   Food   0.9
2  01/02/1990  Agric   1.2
3  01/02/1990   Food   0.9
+5
source

lreshape

df=pd.lreshape(df2, {'Date': ["Date","Date"], 'Beta': ['Agric', 'Food']})
df['Sector']=sorted(df2.columns.tolist()[1:3]*2)

   Out[654]: 
         Date  Beta Sector
0  01/01/1990   1.3  Agric
1  01/02/1990   1.2  Agric
2  01/01/1990   0.9   Food
3  01/02/1990   0.9   Food

48

df=pd.lreshape(df2, {'Date':['Date']*2, 'Beta': df2.columns.tolist()[1:3]})
df['Sector']=sorted(df2.columns.tolist()[1:3]*2)

Sector,

import itertools
list(itertools.chain.from_iterable(itertools.repeat(x, 2) for x in df2.columns.tolist()[1:3]))

lreshap ( @Ted Petrou DataFrame, , , , . pandas API , , lreshape -, . , - . , , pandas, lreshape.)

, , github

pd.wide_to_long

dict1 = {'Agric':'A_Agric','Food':'A_Food'}
df2 = df.rename(columns=dict1)
pd.wide_to_long(df2.reset_index(),['A'],i='Date',j='Sector',sep='_',suffix='.').reset_index().drop('index',axis=1).rename(columns={'A':'Beta '})

Out[2149]: 
         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
+4

Source: https://habr.com/ru/post/1683771/


All Articles