I have a Pandas dataframe with a multiindex, the result of a pivot (as in the pivot pandas function description)
df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two',
'two'],
'bar': ['A', 'B', 'C', 'A', 'B', 'C'],
'baz': [1, 2, 3, 4, 5, 6],
'zoo': ['x', 'y', 'z', 'q', 'w', 't']})
df
foo bar baz zoo
0 one A 1 x
1 one B 2 y
2 one C 3 z
3 two A 4 q
4 two B 5 w
5 two C 6 t
dp = df.pivot(index='foo', columns='bar', values=['baz', 'zoo'])
dp
baz zoo
bar A B C A B C
foo
one 1 2 3 x y z
two 4 5 6 q w t
I want make it look like this:
bar A B C
foo
one [1,x] [2,y] [3,z]
two [4,q] [5,w] [6,t]
Where the data from the level 0 index are combined in a list... Any ideas how this could be done? Tried agg(list) but that did not work...
One option is to combine columns baz
and zoo
first and then pivot the table:
df['combined'] = list(zip(df.baz, df.zoo))
df.pivot('foo', 'bar', 'combined')
#bar A B C
#foo
#one (1, x) (2, y) (3, z)
#two (4, q) (5, w) (6, t)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.