熊猫将年,季度转换为整数

时间:2019-12-13 11:59:22

标签: python string pandas

在熊猫中,我有一列数据的格式如下:


Period
2018 Q1
2018 Q2
2018 Q3
2018 Q4 
2019 Q1
2019 Q2
2019 Q3
2019 Q4
...

当前dtype格式为对象/字符串。有没有办法将数据转换为int64?我不一定需要datetime格式,但是,如果它是唯一的解决方案,那就没问题了。

提前谢谢

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是将Q替换为空字符串,然后将值转换为整数:

df['Period'] = df['Period'].str.replace(' Q', '').astype(int)
print (df)
   Period
0   20181
1   20182
2   20183
3   20184
4   20191
5   20192
6   20193
7   20194

如果需要日期时间或季度时间段,请使用Series.str.replace和空格to_datetime并使用Series.dt.to_period期间:

df['Dates'] = pd.to_datetime(df['Period'].str.replace('\s+', ''))
df['Per'] = pd.to_datetime(df['Period'].str.replace('\s+', '')).dt.to_period('Q')
print (df)
    Period      Dates     Per
0  2018 Q1 2018-01-01  2018Q1
1  2018 Q2 2018-04-01  2018Q2
2  2018 Q3 2018-07-01  2018Q3
3  2018 Q4 2018-10-01  2018Q4
4  2019 Q1 2019-01-01  2019Q1
5  2019 Q2 2019-04-01  2019Q2
6  2019 Q3 2019-07-01  2019Q3
7  2019 Q4 2019-10-01  2019Q4