Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获取熊猫多索引';以列表形式显示的值?_Python_List_Pandas - Fatal编程技术网

Python 如何获取熊猫多索引';以列表形式显示的值?

Python 如何获取熊猫多索引';以列表形式显示的值?,python,list,pandas,Python,List,Pandas,我有一个带有多索引的熊猫数据帧。我想得到一个包含多索引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(

我有一个带有多索引的熊猫数据帧。我想得到一个包含多索引
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
输出:

我想输出如下数据帧:

      output
bar  ['one','two']
baz  ['one','two']
foo  ['one','two']
qux  ['one','two']

如何操作?非常感谢。

您可以将数据馈送到
pd.DataFrame
构造函数,然后使用
groupby

res = pd.DataFrame(df.index.values.tolist(), columns=['idx1', 'idx2'])\
        .groupby('idx1')['idx2'].apply(list)

print(res)

idx1
bar    [one, two]
baz    [one, two]
foo    [one, two]
qux    [one, two]
Name: idx2, dtype: object

您可以馈送到
pd.DataFrame
构造函数,然后使用
groupby

res = pd.DataFrame(df.index.values.tolist(), columns=['idx1', 'idx2'])\
        .groupby('idx1')['idx2'].apply(list)

print(res)

idx1
bar    [one, two]
baz    [one, two]
foo    [one, two]
qux    [one, two]
Name: idx2, dtype: object
与和
列表一起使用

df1 = (df.reset_index()
        .groupby('level_0')['level_1']
        .apply(list)
        .rename_axis(None)
        .to_frame('output'))
或(0.20.0+中新增):

与和
列表一起使用

df1 = (df.reset_index()
        .groupby('level_0')['level_1']
        .apply(list)
        .rename_axis(None)
        .to_frame('output'))
或(0.20.0+中新增):