pandas - 基于子级别的分层索引

标签 pandas

我有一个数据框,如下所示。如何选择第二个索引位于 ['two','third'] 中的行?

index = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'],
                               ['one', 'two', 'three']],
                       labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3],
                               [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]])
hdf = DataFrame(np.random.randn(10, 3), index=index,
            columns=['A', 'B', 'C'])

In [3]: hdf
Out[3]: 
                  A         B         C
foo one   -1.274689  0.946294 -0.149131
    two   -0.015483  1.630099  0.085461
    three  1.396752 -0.272583 -0.760000
bar one   -1.151217  1.269658  2.457231
    two   -1.657258 -1.271384 -2.429598
baz two    1.124609  0.138720 -1.994984
    three  0.124298 -0.127099 -0.409736
qux one    0.535038  1.139026  0.414842
    two    0.287724  0.461041 -0.268918
    three -0.259649  0.226574 -0.558334

最佳答案

使用 DataFrame 的 select 的一种方法方法:

In [4]: hdf.select(lambda x: x[1] in ['two', 'three'])
Out[4]: 
                  A         B         C
foo two   -0.015483  1.630099  0.085461
    three  1.396752 -0.272583 -0.760000
bar two   -1.657258 -1.271384 -2.429598
baz two    1.124609  0.138720 -1.994984
    three  0.124298 -0.127099 -0.409736
qux two    0.287724  0.461041 -0.268918
    three -0.259649  0.226574 -0.558334

关于pandas - 基于子级别的分层索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13899914/

相关文章:

python - 'read_csv'数据的内存与原始数据不同

python - 标记一列中的 ID 第一次出现在另一列中

pandas - Matplotlib 的 axhline 函数与日期时间对象

python - 有没有一种方法可以根据值从 Pandas DataFrame 中提取索引

python - 当尝试替换 .csv 文件中的值时,会出现错误

python - Pandas :沿着多索引的第一层切片

python - 如何在 pandas 中对齐 dfs

python - 使用 Pandas 加入 2 CSV

python - 使用列表中的搜索词从文本中获取字数的最快方法?

python - 删除 Pandas 列名称中的小数