我想获取与数据框中某些条件匹配的值的行和列标签。只是为了让它有趣,我需要它使用分层(多)索引。例如:
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 中真的有那么难吗?
最佳答案
使用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/