How to reformat existing dataframe

68 Views Asked by At

I have following dataframe in python:

geographical area area deep indoor pop deeep indoor area indoor pop indoor area incar pop incar
A 1 2 3 4 5 6
B 7 8 9 10 11 12
C 13 14 15 16 17 18

and the idea is to convert it somehow to this:

deep indoor area pop
A 1 2
B 7 8
C 13 14
indoor area pop
A 3 4
B 9 10
C 15 16
incar area pop
A 5 6
B 11 12
C 17 18

I really don't see any way doing this. I'm lost :-) Any ideas or links to possible solutions are very much appreciated!

1

There are 1 best solutions below

2
Naveed On

just use loc to select the columns you need and rename the geography column for each of the three cases. you need them as three separate DF, per your question

df.loc[:,['geographical area','area deep indoor','pop deep indoor']].rename(columns={'geographical area': 'deep indoor'})
    deep indoor     area deep indoor    pop deep indoor
0   A   1   2
1   B   7   8
2   C   13  14
df.loc[:,['geographical area','area indoor','area indoor']].rename(columns={'geographical area': 'indoor'})
indoor  area indoor     area indoor
0   A   3   3
1   B   9   9
2   C   15  15

df.loc[:,['geographical area','area incar','pop incar']].rename(columns={'geographical area': 'incar'})
    incar   area incar  pop incar
0   A   5   6
1   B   11  12
2   C   17  18