'Keep only last six months data in Python Pandas dataframe

from dateutil.relativedelta import relativedelta

I did

df['Date'] = pd.to_datetime(df['Date'])
six_months = date.today() - relativedelta( months = +6)
df = df.loc[(df['Date'] >= six_months)]

I kept getting following error TypeError: '>=' not supported between instances of 'str' and 'datetime.date'

Can someone help me to grap just last six months data from df?



Solution 1:[1]

Try this code

df['Date'].last('6M')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 baovolamada