[英]How do I combine data from a Pandas DataFrame with a multiindex into a list
I have a Pandas dataframe with a multiindex, the result of a pivot (as in the pivot pandas function description) 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? 0 级索引中的数据在哪里组合在一个列表中......有什么想法可以做到这一点吗? Tried agg(list) but that did not work...
试过 agg(list) 但这没有用......
One option is to combine columns baz
and zoo
first and then pivot the table:一种选择是先组合列
baz
和zoo
,然后组合 pivot 表:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.