Python 按条件获取数据帧中元素的索引

Python 按条件获取数据帧中元素的索引,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,我有这样一个数据帧: df = pd.DataFrame(columns=['A', 'B', 'C '], index=['D', 'E', 'F'], data = np.arange(0, 9, 1).reshape(3,3)) A B C D 0 1 2 E 3 4 5 F 6 7 8 我需要的是提取所有元素的行和列索引,如果它们小于4。这似乎很基本,但我做不到 例如,我想要的是: {'D A': 0, 'D B':1,...} 首先将大于或等于4

我有这样一个数据帧:

df = pd.DataFrame(columns=['A', 'B', 'C '], 
index=['D', 'E', 'F'], data = np.arange(0, 9, 1).reshape(3,3))

   A  B  C 
D  0  1  2
E  3  4  5
F  6  7  8
我需要的是提取所有元素的行和列索引,如果它们小于4。这似乎很基本,但我做不到

例如,我想要的是:

 {'D A': 0, 'D B':1,...}

首先将大于或等于4的值屏蔽为
np.nan
,然后使用
stack
方法,默认情况下该方法会删除
nan
值,现在如果提取索引,它将是您需要的索引:

df.where(df < 4).stack().index.values
# array([('D', 'A'), ('D', 'B'), ('D', 'C '), ('E', 'A')], dtype=object)

我可以以数据结构的形式获取它吗?因为我需要处理结果您可以使用
to_dict
方法将堆栈结果转换为字典。请参阅更新。
df.where(df < 4).stack().to_dict()
# {('D', 'A'): 0.0, ('D', 'B'): 1.0, ('D', 'C '): 2.0, ('E', 'A'): 3.0}
df.style.applymap(lambda x: 'color: %s' % 'red' if x < 4 else '')