如何将期间字符串转换为实际的期间类型 [英] How to convert Period string to actual Period type

查看:52
本文介绍了如何将期间字符串转换为实际的期间类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列数据,例如'1971q1''1972q2'等(年份,后跟季度).

I have a column of data such as '1971q1', '1972q2', etc. (year followed by quarter) When I do:

print(type(df.Quarterly))

答案是Series

我需要做的是将此列转换"/转换为纯正的pd.Period类型,以便对其进行简单的时间代数处理.谢谢

What I need is to "cast"/convert this column to a genuine pd.Period type so I can do simple time algebra with it. Thank you

推荐答案

,您可以使用假设您具有以下DF:

In [517]: x
Out[517]:
  str_col
0  1971q1
1  1971q2
2  1971q3
3  1971q4
4  1972q1
5  1972q2
6  1972q3
7  1972q4

In [518]: x.dtypes
Out[518]:
str_col    object
dtype: object

让我们创建一个新的期间"列:

let's create a new 'period' column:

In [519]: x['period'] = pd.PeriodIndex(x.str_col, freq='Q')

In [520]: x
Out[520]:
  str_col period
0  1971q1 1971Q1
1  1971q2 1971Q2
2  1971q3 1971Q3
3  1971q4 1971Q4
4  1972q1 1972Q1
5  1972q2 1972Q2
6  1972q3 1972Q3
7  1972q4 1972Q4

In [521]: x.dtypes
Out[521]:
str_col    object
period     object
dtype: object

现在我们可以进行时间代数",例如,让我们从每个周期中减去四分之一:

now we can do "time algebra", for example let's subtract one quarter from each period:

In [525]: x.period - 1
Out[525]:
0   1970Q4
1   1971Q1
2   1971Q2
3   1971Q3
4   1971Q4
5   1972Q1
6   1972Q2
7   1972Q3
Name: period, dtype: object

或者,您可以将str_col列强制转换为常规Pandas/NumPy datetime:

alternatively you can cast the str_col column to regular Pandas/NumPy datetime:

In [527]: pd.to_datetime(x.str_col, errors='coerce')
Out[527]:
0   1971-01-01
1   1971-04-01
2   1971-07-01
3   1971-10-01
4   1972-01-01
5   1972-04-01
6   1972-07-01
7   1972-10-01
Name: str_col, dtype: datetime64[ns]

这篇关于如何将期间字符串转换为实际的期间类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆