Get row and column in Pandas for a cell with a certain value Get row and column in Pandas for a cell with a certain value pandas pandas

Get row and column in Pandas for a cell with a certain value


Create a df with NaN where your_value is not found.
Drop all rows that don't contain the value.
Drop all columns that don't contain the value

    a = df.where(df=='your_value').dropna(how='all').dropna(axis=1)

To get the row(s)

    a.index

To get the column(s)

    a.columns  


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))]

out:

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

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

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))]


You can simply create a mask of the same shape than your df by calling df == 'title'.You can then combines this with the df.where() method, which will set all fields to NA that are different to your keyword, and finally you can use dropna() to reduce it to all valid fields. Then you can use the df.columnnsand df.indexlike you're use to.

df = pd.DataFrame({"a": [0,1,2], "b": [0, 9, 7]})print(df.where(df == 0).dropna().index)print(df.where(df == 0).dropna().columns)#Int64Index([0], dtype='int64')#Index(['a', 'b'], dtype='object')