Home > Mobile >  Pandas Dataframe - Search by index
Pandas Dataframe - Search by index

Time:10-15

I have a dataframe where the index is a timestamp.

DATE                VALOR   
2020-12-01 00:00:00 0.00635
2020-12-01 01:00:00 0.00941
2020-12-01 02:00:00 0.01151
2020-12-01 03:00:00 0.00281
2020-12-01 04:00:00 0.01080
... ...
2021-04-30 19:00:00 0.77059
2021-04-30 20:00:00 0.49285
2021-04-30 21:00:00 0.49057
2021-04-30 22:00:00 0.50339
2021-04-30 23:00:00 0.48792

I´m searching for a specific date

drop.loc['2020-12-01 04:00:00']

VALOR    0.0108
Name: 2020-12-01 04:00:00, dtype: float64

I want the return for the index of search above.

In this case is line 5. After I want to use this value to do a slice in the dataframe

drop[:5]

Thanks!

CodePudding user response:

It looks like you want to subset drop up to index '2020-12-01 04:00:00'.

Then simply do this: drop.loc[:'2020-12-01 04:00:00']

No need to manually get the line number.

output:

                       VALOR
DATE                        
2020-12-01 00:00:00  0.00635
2020-12-01 01:00:00  0.00941
2020-12-01 02:00:00  0.01151
2020-12-01 03:00:00  0.00281
2020-12-01 04:00:00  0.01080

If you really want to get the position:

pos = drop.index.get_loc(key='2020-12-01 04:00:00')  ## returns: 4
drop[:pos 1]
  • Related