Reputation: 73
I am having small problem. I have a practice data frame (still learning) with coulmn which has year and quarters per-defined like so
Date Column2 Column3
2004 Q-1 Other data Other data
2004 Q-2 Other Data Other data
up to 2019. Pandas sees this as object, and I have been trying to convert it to date and quarter.
I have tried:
df['Date'] = df['Date'].str.replace(' Q-', '').astype(int)
which gave error
invalid literal for int() with base 10: '2019 4'
df['Date'] = df.ddate.dt.to_period("Q")
but my df doesn't have ddate attribute
df['Date'] = pd.to_datetime(df['Date'], format='%Y %q')
with error:
'q' is a bad directive in format '%Y %q'
I am currently out of ideas of how to convert this so pandas can read this as quarters per year.
Upvotes: 3
Views: 275
Reputation: 26676
You weren't as explicit. Do you want the date extracted from year quarter? Looks to me thats likely. If it is, please my attempt below. If aint, clarify to get help. Staggered it to be readable (I am a readable code enthusiast, like to demistify coding :-) );
data['Date'] = data['Date'].str.replace(r'-','')
data['Date'] = data['Date'].str.replace(' ',r'')
data['Date']=pd.to_datetime(data['Date'])
If wanted EndMonth:
data.set_index('Date', inplace=True)
data['EndMonth']= data.index.to_period('M').to_timestamp('M')
Upvotes: 1