首页 > 解决方案 > 引用和计数属于层次结构的列

问题描述

我希望能够引用更高层次的列,并能够计算列数并列出它拥有的列的名称。

这是数据集:

import pandas as pd
import numpy as np
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
df = pd.DataFrame(np.random.randn(3, 8), index=['A', 'B', 'C'], columns=arrays)

这是输出:

        bar                 baz                 foo                 qux
        one       two       one       two       one       two       one       two
A  0.050343 -0.525009  0.126593 -0.332575 -1.233224  0.415279  1.097570  0.096461
B  2.371400 -0.184967 -0.470547  2.203325 -0.914778  0.392034  0.398723  1.047543
C  0.977506  1.606047 -0.993077 -0.804615  0.654538 -0.099860  0.679309 -1.313231

我试图了解如何查找属于某个层次结构的列数(例如bar.

我的尝试似乎不起作用,因为我期望 2 作为print(len())函数的输出和函数[one, two]的输出print()

尝试1:

print(len(df.columns))
print(df.columns)
8
MultiIndex([('bar', 'one'),
            ('bar', 'two'),
            ('baz', 'one'),
            ('baz', 'two'),
            ('foo', 'one'),
            ('foo', 'two'),
            ('qux', 'one'),
            ('qux', 'two')],
           )

尝试2:

print(len(df.columns[1]))
print(df.columns[1])
2
('bar', 'two')

尝试 3:

print(len(df.columns['bar'])
print(df.columns['bar'])
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

所需的输出将是:

2
['one','two']

标签: pythonpandasmulti-index

解决方案


普通选择呢?:

>>> df['bar']
        one       two
A -0.671483  0.349299
B  0.475603  0.576552
C -0.141044 -1.063308
>>> df['bar'].shape
(3, 2)
>>> df['bar'].columns
Index(['one', 'two'], dtype='object')

推荐阅读