Home > other >  Find the row and column index of the particular value in Dataframe
Find the row and column index of the particular value in Dataframe

Time:01-03

I have to find the row and column index of the particular value from the dataframe. I have the code to find the row index based on the column name. But not sure how to find both row and column indexes.

Current Table:

0 1 2 3 4
VT1 Date Time Glen 1600
VT2 04/16 4:00 Cof 1600
VT3 04/18 5.00 1750 NAN
VT4 04/19 7.00 1970 NAN

From the above table, need to find the row and column index of the value 'Date'.

Code to find row index based on column:

print(df[df[1]=='Date'].index.values)

But we need to find the both the indexes without giving column name.

CodePudding user response:

You can use where and stack, then convert the index tolist:

df.where(df.eq('Date')).stack().index.tolist()

Output:

[(0, '1')]

NB. if you have more than one match this will give you a list of all matches. Example with "1600":

df.where(df.eq('1600')).stack().index.tolist()
# [(0, '4'), (1, '4')]

CodePudding user response:

Use numpy.where for indices, filter index and columns names to arrays, if need pairs in tuples use zip:

i, c = np.where(df.eq('Date'))

idx = df.index[i]
cols = df.columns[c]

tuples = list(zip(idx, cols))
print (tuples)
[(0, '1')]
  • Related