0

How do I achieve such an operation :

import pandas as pd

df = pd.DataFrame({'foo':[1,2,3],'bar_1':[11,21,31],'bar_2':[12,22,32],'bar_3':[13,23,33]})
print(df)

df_pivot = pd.DataFrame({'foo':[1,2,3,1,2,3,1,2,3],'bar_id':['bar_1','bar_1','bar_1','bar_2','bar_2','bar_2','bar_3','bar_3','bar_3'],'bar':[11,21,31,12,22,32,13,23,33]})
print(df_pivot)

giving :

   foo  bar_1  bar_2  bar_3
0    1     11     12     13
1    2     21     22     23
2    3     31     32     33

   foo bar_id  bar
0    1  bar_1   11
1    2  bar_1   21
2    3  bar_1   31
3    1  bar_2   12
4    2  bar_2   22
5    3  bar_2   32
6    1  bar_3   13
7    2  bar_3   23
8    3  bar_3   33

I want to keep (and repeat all the foo columns) but separate the bar ones (and keeping a trace of it with bar_id).

I looked at pandas.pivot, but I cannot find a way.

Thanks :)

louis
  • 21
  • 5

0 Answers0