-1

I am trying to bring the pandas dataframe from wide to long but I cannot find a good way to do it. Any suggestion to do this through pandas?

data = {'colour':["red", "blue", "yellow", "red", "yellow"],
        'apple':[1, 2, 4, 5, 6], 
        'organge': [3, 4, 5, 7, 8],
        'watermelon': [7, 8, 9, 1, 0]}
df = pd.DataFrame(data)
df

   colour  apple  organge  watermelon
0     red      1        3           7
1    blue      2        4           8
2  yellow      4        5           9
3     red      5        7           1
4  yellow      6        8           0

Expected result:

        fruit  red  blue  yellow
0       apple    6     2      10
1     organge   10     4      13
2  watermelon    8     8       9
codedancer
  • 1,504
  • 9
  • 20

1 Answers1

1

So you can do groupby with T

out = df.groupby('colour').sum().T
Out[45]: 
colour      blue  red  yellow
apple          2    6      10
organge        4   10      13
watermelon     8    8       9

Or

out = df.set_index('colour').T.sum(level=0,axis=1)
Out[48]: 
colour      red  blue  yellow
apple         6     2      10
organge      10     4      13
watermelon    8     8       9
BENY
  • 317,841
  • 20
  • 164
  • 234
  • "Using the level keyword in DataFrame and Series aggregations is deprecated and will be removed in a future version. Use groupby instead." Should be `.groupby(level=0, axis=1).sum()` moving forward. – Henry Ecker Sep 15 '21 at 15:42
  • 1
    @BENY. `df.groupby('colour', sort=False).sum().T` to get expect outcome. – Corralien Sep 15 '21 at 15:58