【发布时间】:2016-10-28 18:11:21
【问题描述】:
我想获取匹配数据框中某些条件的值的行和列标签。为了保持有趣,我需要它与分层(多)索引一起使用。例如:
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'))]
请注意,我想要一个通用解决方案,它不依赖于单调的索引或我的示例中的特定选择。这个问题已经被问过很多次了,但答案并不笼统:
- index and column for the max value in pandas dataframe:依靠排序找到最大值
- Pandas dataframe: return row AND column of maximum value(s):不概括
- Retrieve indices of NaN values in a pandas dataframe: 不返回行标签
- Return list of indices/index where a min/max value occurs in a pandas dataframe: 不能一概而论
- Pandas: Get each value's index and columns values:不概括/使用迭代
Pandas 真的这么难吗?
【问题讨论】: