将 period[Q-DEC] 列转换为数据帧到 Python 中的字符串

Converting period[Q-DEC] column into a dataframe to a string in Python

我正在尝试将 period[Q-DEC] 列转换为用于建模的字符串。

帮助我做到了这一点。

我目前的数据:

df = {'Month': [1, 8], 'Year': [2015, 2020]}
df = pd.DataFrame(data = df)
df['Quarter'] = (pd.to_datetime(df[['Month','Year']].astype(str)
               .agg('-'.join,1).radd("01-"),dayfirst=True).dt.to_period('Q'))

print(df)
df.dtypes

它给了我输出

   Month  Year Quarter
0      1  2015  2015Q1
1      8  2020  2020Q3
Month              int64
Year               int64
Quarter    period[Q-DEC]
dtype: object

令人惊讶的是,我没有看到很多关于如何将 period 转换为字符串的答案。我尝试了 中的几种解决方案。感谢任何提示!

.astype(str)

df.Quarter=df.Quarter.astype(str)
df.dtypes

Month       int64
Year        int64
Quarter    object
dtype: object

print(df)
 Month    Year Quarter
0      1  2015  2015Q1
1      8  2020  2020Q3

你可以试试,也可以改变你创建日期时间的方式

df['Quarter'] = pd.to_datetime(df.Year*10+df.Month,format='%Y%m').dt.to_period('q').astype(str)
Out[19]: 
0    2015Q1
1    2020Q3
dtype: object