我有一个带有 MultiIndex 的 pandas DataFrame。我想得到一个包含 MultiIndex level0
和 level1
的列表,就像这样 [level0,[level1-1,level1-2,(...)]
.
例如:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
df = pd.DataFrame(np.random.randn(8), index=arrays,columns=['values'])
df
输出:
values
bar one 2.171200
two -0.665047
baz one 0.474036
two 0.082408
foo one 1.820585
two 0.698537
qux one 1.163479
two 0.129044
我想输出这样的数据框:
output
bar ['one','two']
baz ['one','two']
foo ['one','two']
qux ['one','two']
如何?非常感谢。
最佳答案
使用reset_index
与 groupby
和列表
:
df1 = (df.reset_index()
.groupby('level_0')['level_1']
.apply(list)
.rename_axis(None)
.to_frame('output'))
或MultiIndex.to_frame
( Pandas 0.20.0+ 中的新功能):
df1 = df.index.to_frame().groupby(0)[1].apply(list).rename_axis(None).to_frame('output')
print (df1)
output
bar [one, two]
baz [one, two]
foo [one, two]
qux [one, two]
关于python - 如何以列表的形式获取 pandas MultiIndex 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51478208/