1

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.
Pravin
  • 241
  • 2
  • 14

2 Answers2

1

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')]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

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')]
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Is there anyway instead of 'equals' can we have contains? basically like the 'in' in the if condition – Pravin Jan 05 '23 at 09:12
  • @Pravin something like replacing `df.eq('1600')` with `df.apply(lambda s: s.str.contains('1600'))`? – mozway Jan 05 '23 at 09:15