How to select rows where date is in index in Python Pandas DataFrame?

Tags: , , ,



I have DataFrame in Pythonlike below where data is in index (we can name this column “date”):

enter image description here

and I would like to select all column of this DF where data in index is > than 01.01.2020, how can I do it? (be aware that date is in index).

Answer

Use boolean indexing:

df.index = pd.to_datetime(df.index, dayfirst=True)
df1 = df[df.index > '2020-01-01']

Or:

df.index = pd.to_datetime(df.index, dayfirst=True)
df1 = df[df.index > pd.to_datetime('2020-01-01')]


Source: stackoverflow