Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas find Row number for matching values

Tags:

python

pandas

I can find the matching row with this but how do I get the row number of the df?

y = df.loc [ df [ 'month' ] == df3 [ 'month' ] ]

I need y to be the row count.

I can get the index value, but the index for df is also a date.

Thanks.

like image 627
diogenes Avatar asked Feb 08 '18 03:02

diogenes


2 Answers

One method is reindexing since you want the index to be integers rather than dates.

y = df.loc[df['month'] == df3['month' ]].reset_index().index
like image 190
3novak Avatar answered Oct 24 '22 19:10

3novak


If you don't want to reset the index you can simply add a column with a row count:

import pandas as pd

df = pd.DataFrame({'month':[1,1,1,1,2,2,2]})
df.insert(0, 'row_num', range(0,len(df)))  # here you insert the row count
df3 = pd.DataFrame({'month':[2,2,2,1,2,2,2]})
y = df.loc [ df [ 'month' ] == df3 [ 'month' ] ]

The content of the df

>>> df
   row_num  month
0        0      1
1        1      1
2        2      1
3        3      1
4        4      2
5        5      2
6        6      2

Result

>>> y['row_num']
3    3
4    4
5    5
6    6
like image 25
Guiem Bosch Avatar answered Oct 24 '22 18:10

Guiem Bosch