python-3.x - 当月份为小数位时,将 float 转换为日期时间(YYYY.MM float )

标签 python-3.x pandas

这是我的数据:

d = pd.DataFrame({'date': [2021.01, 2021.02, 2021.03, 2021.04],
                   'value': [2, 3, 4, 1]})

d

enter image description here

我想将日期列转换为日期。目前是 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/

相关文章:

python - 使用带有 for 循环的字典来比较值

python - 使用 Pandas,如何对两列使用 if/then 逻辑来填充另一列?

python - 在 Pandas 中获取带有向量的数据帧的点积,并返回数据帧

python - 从 timedelta 构建 Pandas pd.tseries.offsets

python - pandas:检查引用列表中的匹配值的系列,为每个匹配生成新记录

python - 为什么多行字符串在打印或写入时会发生变化? (Windows 上的 Python 3.6)

python - 无法打开 Python。错误 0xc000007b

python - 使用特定编码从 C 代码运行 python 命令

python - 如何将元组元素组合到Python中的列表中

python - Pandas 获得在同一列中一起使用的最频繁的值