Home > Blockchain >  Transpose repeated values into multiple columns
Transpose repeated values into multiple columns

Time:09-08

I have this dataframe:

index Col1 Col2 Col3
0 A Day1 10
1 A Day2 9
2 A Day3 11
3 B Day1 12
4 B Day2 7
5 B Day3 5
6 C Day1 9
7 C Day2 10
8 C Day3 6

I want to transpose the columns so that it looks like this

Date A B C
Day1 10 12 9
Day2 9 7 10
Day3 11 5 6

Is there a way I can do that with Python? Thank you!

CodePudding user response:

Yes, it's called pivoting.

df = pd.DataFrame({'Col1': ['A'] * 3   ['B'] * 3   ['C'] * 3, 'Col2': np.tile(['Day1', 'Day2', 'Day3'], 3), 'Col3': [10, 9, 11, 12, 7, 5, 9, 10, 6]})
df.pivot('Col2', 'Col1', 'Col3')

CodePudding user response:

You can do it like @Alex shows you also there is another way that provides you more customization which is pivot_table which enables you to get average or any other aggregation on your data the default is mean

df.pivot_table(index="Col2",columns="Col1",values='Col3',aggfunc=sum)

enter image description here

df.pivot_table(index="Col2",columns="Col1",values='Col3',aggfunc='count')

enter image description here

  • Related