这是我的数据:
d = pd.DataFrame({'date': [2021.01, 2021.02, 2021.03, 2021.04],
'value': [2, 3, 4, 1]})
d
我想将日期列转换为日期。目前是 float 月份,小数点后 (YYYY.mm)
这不起作用:
pd.to_datetime(d['date'], format='%Y.%m', errors='coerce').dt.to_period('m')
最佳答案
您可以乘以 100 并使用整数作为 to_datetime
的输入:
pd.to_datetime(d['date'].mul(100).astype(int), format='%Y%m').dt.to_period('m')
注意。即使没有转换为整数,它似乎也可以工作,但我仍然会这样做,或者使用round
来避免浮点歧义(取决于想要的输出)
输出:
0 2021-01
1 2021-02
2 2021-03
3 2021-04
Name: date, dtype: period[M]
关于python-3.x - 当月份为小数位时,将 float 转换为日期时间(YYYY.MM float ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71077284/