newbie pandas
newbie pandas

Reputation: 13

How to remove last 2 months records from 2 years records based on Date?

I have a DataFrame which having 2 years data, need to sort and remove recent 2 months records.

Ship_Date        Id

2019-10-29       i1 
2019-10-29       i2
2019-10-28       i3
2019-10-28       i4
....

I tried in this way but getting KeyError:

df.index = pd.DatetimeIndex(df.pop('Ship_Date'))
df.sort_index().last('2M').drop()

Any help please

Upvotes: 0

Views: 213

Answers (1)

jezrael
jezrael

Reputation: 862741

Use DataFrame.drop with DatetimeIndex:

df.index = pd.DatetimeIndex(df.pop('Ship_Date'))
df = df.drop(df.sort_index().last('2M').index)

Upvotes: 1

Related Questions