如何在整个数据框中搜索特定值并返回其列和行索引

Yig*_*ong 2 python search dataframe pandas

在熊猫中,我想在整个数据框中搜索特定值并返回其行和列索引。

例如:

    apple pear orange banana
cat    1     2     3     4
dog    5     6     7     8    
fish   9     10    11    12
bird   13    14    15    16
Run Code Online (Sandbox Code Playgroud)

输入:10

输出:鱼,梨

jez*_*ael 5

使用np.where的指数匹配和索引的比赛第一个值:

i, c = np.where(df == 10)

print ((df.index[i][0], df.columns[c][0]))
('fish', 'pear')
Run Code Online (Sandbox Code Playgroud)

如果数据中不存在可能的值,则使用next默认值:

print ((next(iter(df.index[i]), 'no match'), next(iter(df.columns[c]), 'no match')))
('fish', 'pear')
Run Code Online (Sandbox Code Playgroud)