python - 获取 Pandas 数据框中选定值的行和列标签

标签 python pandas indexing

我想获取与数据框中某些条件匹配的值的行和列标签。只是为了让它有趣,我需要它使用分层(多)索引。例如:

df = pd.DataFrame(np.arange(16).reshape(4, 4), columns=pd.MultiIndex.from_product((('a', 'b'), ('x', 'y'))))

    a       b    
    x   y   x   y
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15

现在假设我想要元素的行和列标签

df % 6 == 0

       a             b       
       x      y      x      y
0   True  False  False  False
1  False  False   True  False
2  False  False  False  False
3   True  False  False  False

我想得到

[(0, ('a', 'x')), (1, ('b', 'x')), (3, ('a', 'x'))]

请注意,我想要一个通用 解决方案,它不依赖于单调索引或我示例中的特定选择。这个问题已经被问过很多次了,但答案并不笼统:

这在 Pandas 中真的有那么难吗?

最佳答案

使用np.where获取真值的序数索引:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(16).reshape(4, 4), 
                  columns=pd.MultiIndex.from_product((('a', 'b'), ('x', 'y'))))

mask = (df % 6 == 0)
i, j = np.where(mask)
print(list(zip(df.index[i], df.columns[j])))

产量

[(0, ('a', 'x')), (1, ('b', 'x')), (3, ('a', 'x'))]

关于python - 获取 Pandas 数据框中选定值的行和列标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38041936/

相关文章:

python - 使用 datetime.date 对象列表过滤数据帧行

Mysql分组不使用索引

indexing - ElasticSearch索引geo_shape错误rMapperParsingException解析失败

Python 和 Selenium : identification of elements in 'tables within tables' without using a keyword

python - 张量维度的大小范围 - tf.range

python - 在 pandas 导入上过滤 pytables 表

python - pandas groupby 有很多键

python - 从一个列表替换另一个列表中间的值

python - 在 App Engine 中处理大型云存储文件

python - 避免重复 Django URL