Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get integer index values from filtered pandas dataframe

Having a pd.DataFrame with a DateTimeIndex, I am looking for the index integer values after applying a filter.

Here's the df:

import numpy as np
import pandas as pd

df = pd.DataFrame(
    data=np.random.randint(low=0, high=10, size=(5, 2)),
    index=pd.date_range(start="2020-12-31", periods=5)
)
df

            0  1
2020-12-31  7  6
2021-01-01  2  6
2021-01-02  5  2
2021-01-03  2  3
2021-01-04  4  7

Let's apply some filter:

df_selection = df.loc[pd.date_range(start="2021-01-02", periods=2), :]
df_selection

            0  1
2021-01-02  9  0
2021-01-03  9  5

Finally, I am looking for the integer index values of the filtered data frame. That is I need to get [2, 3].

like image 986
Andi Avatar asked Dec 05 '25 18:12

Andi


1 Answers

Assuming df is sorted by index:

np.searchsorted(df.index, df_selection.index)

Output:

array([2, 3])

In general, you can do:

np.where(df.index.isin(df_selection.index))

output:

(array([2, 3]),)
like image 190
Quang Hoang Avatar answered Dec 08 '25 13:12

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!