-2

I have a dataframe that looks like the following image: my df

How in pandas unpivot this data, that look like image down? finish data

I try do it with df.unstack(), but nothing

A.G.A
  • 1

2 Answers2

1

Use stack with level parameter:

df.stack(level=[0,1]).reset_index()

Output:

   level_0 level_1     level_2 level_3   0
0        A       Y  01.02.2018  City 1   1
1        A       Y  01.02.2018  City 2   2
2        A       Y  01.02.2018  City 3   3
3        A       Y  01.03.2018  City 1   2
4        A       Y  01.03.2018  City 2   3
5        A       Y  01.03.2018  City 3   4
6        B       U  01.02.2018  City 1   4
7        B       U  01.02.2018  City 2   5
8        B       U  01.02.2018  City 3   6
9        B       U  01.03.2018  City 1   5
10       B       U  01.03.2018  City 2   6
11       B       U  01.03.2018  City 3   7
12       C       O  01.02.2018  City 1   7
13       C       O  01.02.2018  City 2   8
14       C       O  01.02.2018  City 3   9
15       C       O  01.03.2018  City 1   8
16       C       O  01.03.2018  City 2   9
17       C       O  01.03.2018  City 3  10
18       D       P  01.02.2018  City 1  10
19       D       P  01.02.2018  City 2  11
20       D       P  01.02.2018  City 3  12
21       D       P  01.03.2018  City 1  11
22       D       P  01.03.2018  City 2  12
23       D       P  01.03.2018  City 3  13

And, cleanup column names you can use set_axis:

df.stack(level=[0,1]).reset_index().set_axis(['', '', 'date','name city','value'], axis=1, inplace=False)

Output (head):

               date name city  value
0  A  Y  01.02.2018    City 1      1
1  A  Y  01.02.2018    City 2      2
2  A  Y  01.02.2018    City 3      3
3  A  Y  01.03.2018    City 1      2
4  A  Y  01.03.2018    City 2      3
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

Another approach would be:

index = df.loc[:, df.columns.get_level_values(1)==''].columns.tolist()
values = df.loc[:, df.columns.get_level_values(1)!=''].columns.tolist()
df = df.melt(id_vars=index, value_vars=values)

You can afterwards name the columns as you wish.

zipa
  • 27,316
  • 6
  • 40
  • 58