gpt4 book ai didi

python - 在 Pandas 中分配日期

转载 作者:行者123 更新时间:2023-11-30 22:34:51 26 4
gpt4 key购买 nike

我正在尝试将 Pandas 数据框中的月份列转换为日期。新值将每月添加到该时间序列中

    month                      Values
0 2006M01 279.59
1 2006M02 280.90
2 2006M03 282.89
3 2006M04 284.32
4 2006M05 284.76
5 2006M06 284.68
6 2006M07 284.19
7 2006M08 284.38
8 2006M09 286.04
9 2006M10 286.07
10 2006M11 286.43
11 2006M12 286.43

最佳答案

使用to_datetime使用 format 参数:

df['date'] = pd.to_datetime(df['month'], format='%YM%m')
print (df)
month Values date
0 2006M01 279.59 2006-01-01
1 2006M02 280.90 2006-02-01
2 2006M03 282.89 2006-03-01
3 2006M04 284.32 2006-04-01
4 2006M05 284.76 2006-05-01
5 2006M06 284.68 2006-06-01
6 2006M07 284.19 2006-07-01
7 2006M08 284.38 2006-08-01
8 2006M09 286.04 2006-09-01
9 2006M10 286.07 2006-10-01
10 2006M11 286.43 2006-11-01
11 2006M12 286.43 2006-12-01

也可以使用 to_period 转换为月份 :

df['period'] = pd.to_datetime(df['month'], format='%YM%m').dt.to_period('m')
print (df)
month Values period
0 2006M01 279.59 2006-01
1 2006M02 280.90 2006-02
2 2006M03 282.89 2006-03
3 2006M04 284.32 2006-04
4 2006M05 284.76 2006-05
5 2006M06 284.68 2006-06
6 2006M07 284.19 2006-07
7 2006M08 284.38 2006-08
8 2006M09 286.04 2006-09
9 2006M10 286.07 2006-10
10 2006M11 286.43 2006-11
11 2006M12 286.43 2006-12

关于python - 在 Pandas 中分配日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44738620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com