且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取具有特定值的单元格在Pandas中的行和列

更新时间:2022-04-21 22:48:21

您可以做一些冗长而难以阅读的列表理解:

You can do some long and hard to read list comprehension:

# assume this df and that we are looking for 'abc'
df = pd.DataFrame({'col':['abc', 'def','wert','abc'], 'col2':['asdf', 'abc', 'sdfg', 'def']})

[(df[col][df[col].eq('abc')].index[i], df.columns.get_loc(col)) for col in df.columns for i in range(len(df[col][df[col].eq('abc')].index))]

退出:

[(0, 0), (3, 0), (1, 1)]

我应该注意,这是(索引值,列位置)

I should note that this is (index value, column location)

如果您要查找包含某个特定值的任何字符串,也可以将 .eq()更改为 str.contains():

you can also change .eq() to str.contains() if you are looking for any strings that contains a certain value:

[(df[col][df[col].str.contains('ab')].index[i], df.columns.get_loc(col)) for col in df.columns for i in range(len(df[col][df[col].str.contains('ab')].index))]