python - 如何在 Python Pandas 中将日期转换为季度而不重复前 5 年的季度?

标签 python python-3.x pandas datetime python-3.6

我想将日期转换为季度。我用过,

x['quarter'] = x['date'].dt.quarter

        date    quarter
0   2013-1-1          1

但是,明年也会重复同样的情况。

          date    quarter
366   2014-1-1          1

而不是1,我希望(预期结果)季度为5

          date    quarter
366   2014-1-1          5
.
.
.
.
          date    quarter
731   2015-1-1          9

最佳答案

您可以使用简单的数学运算

starting_year = 2013
df['quarter'] = df.year.dt.quarter + (df.year.dt.year - starting_year)*4

    year        quarter
0   2013-01-01  1
0   2014-01-01  5
0   2015-01-01  9
0   2016-01-01  13

关于python - 如何在 Python Pandas 中将日期转换为季度而不重复前 5 年的季度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51706767/

相关文章:

python - 管理 Azure 无服务器函数应用中的连接

python - 我如何获得所有连接?

Python-pandas : How can I simultaneously select all even columns of a big Dataframe

python-3.x - 如何获得一维数据的k均值聚类?

python - 如何循环遍历两个数据帧的列,按键分组并执行计算

python - 为 numpy 数组中的整行赋值

python - 如何将所有单词组合成一个字符串?

仅当时间是整点后 5 点时才使用 Python

python - 我怎样才能允许只对部分模式进行模糊正则表达式匹配?

python - 通过批处理脚本安装带有路径变量的python