Reputation: 123
I have a Pandas Dataframe of the format as shown below:
Month Count
2021-02 100
2021-03 200
Where the "Month" column is obtained from a timestamp using dt.to_period('M').
Now I have to convert this "Month" column to a fiscal quarter and I have used some approaches to convert the Period to a "datetime" object using "to_timestamp", but I get the error
TypeError: unsupported Type Int64Index
Is there another way to approach this problem?
Upvotes: 8
Views: 7861
Reputation: 862761
If working with a column, it is necessary to add .dt
. If omitting it, Pandas tries to convert DatetimeIndex
and if it does not exist, it raises an error, because it called DataFrame.to_timestamp
instead of Series.dt.to_timestamp
:
df['Date'] = df['Month'].to_timestamp()
TypeError: unsupported Type RangeIndex
df['Date'] = df['Month'].dt.to_timestamp()
print (df)
Month Count Date
0 2021-02 100 2021-02-01
1 2021-03 200 2021-03-01
The solution for a fiscal quarter is to use Series.dt.qyear
. Better documentation is here:
df['fquarter'] = df['Month'].dt.qyear
print (df)
Month Count fquarter
0 2021-02 100 2021
1 2021-03 200 2021
Upvotes: 10