0

say I have the following data without a header

0 1 2
a a 1
a b 1
a c 1
b a 2
b b 2
b c 2
c a 3
c b 3
c c 3

I want to get the data in the following format

a b c
a 1 1 1
b 2 2 2
c 3 3 3

I have tried the following but didn't work out

df= df.pivot_table("2","1")

It didn't work for me but it is either wrong or it doesn't work as the df has no header. Any hint will be appreciated!

Kimchi
  • 97
  • 6
  • If there is no defined header, then it is likely integers. – mozway Dec 08 '21 at 18:40
  • `df.pivot(columns=['1'], index=['0'], values='2').rename_axis(None).rename_axis(None, axis=1)` –  Dec 08 '21 at 18:42
  • I am getting an error when reading the index, it can't read the index 0 for some reason. KeyError: '0' – Kimchi Dec 08 '21 at 18:46
  • @mozway I didn't define the headers on purpose. It is a specific type of matrix, the so-called OD matrix. – Kimchi Dec 08 '21 at 18:47
  • @Kimchi try removing the quotes from the column names, e.g. -> `columns=[1], index=[0], values=2` –  Dec 08 '21 at 18:55
  • @Kimchi a dataframe necessarily has column names, what is the output of `print(df.columns)`? – mozway Dec 08 '21 at 19:00
  • 1
    it is solved now, I made a header for the data frame and used @user17242583 line there but without the index as follows: df.pivot( columns='a', values='2').rename_axis(None).rename_axis(None, axis=1) – Kimchi Dec 08 '21 at 19:05

0 Answers0