Find index range of a sequence in dataframe column

Viewed 14

I have a timeseries:

            Sales
2018-01-01  66.65
2018-01-02  66.68
2018-01-03  65.87
2018-01-04  66.79
2018-01-05  67.97
2018-01-06  96.92
2018-01-07  96.90
2018-01-08  96.90
2018-01-09  96.38
2018-01-10  95.57

Given an arbitrary sequence of values, let's say [66.79,67.97,96.92,96.90], how could I obtain the corresponding indices, for example: [2018-01-04, 2018-01-05,2018-01-06,2018-01-07]?

2 Answers

You can use isin:

df.index[df.Sales.isin([66.79,67.97,96.92,96.90])]

returns:

Index(['2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08'], dtype='object')

Use pandas.Series.isin to filter the column Sales then pandas.DataFrame.index to return the row labels (aka index, dates in your df) and finally pandas.Series.to_list to build a list :

vals = [66.79,67.97,96.92,96.90]

result = df[df['Sales'].isin(vals)].index.to_list()

# Output :

print(result)
['2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08']
Related