【问题标题】:Modify datetime column in pandas based on value from another column根据另一列的值修改熊猫中的日期时间列
【发布时间】:2021-12-03 18:28:29
【问题描述】:

我有一列以整数表示月份,还有一个以白天格式存储当前日期的变量。我需要创建一个更新月份的列:

df_final["Date"] = current_day.replace(month=df_final["Month"])

但我收到以下错误:

/venv/lib/python3.8/site-packages/pandas/core/series.py", line 185, in wrapper
    raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'int'>

我不知道为什么,有什么建议吗?

【问题讨论】:

  • 我看到的大部分文档都在使用 .replace(['old value'],'new value'),没有看到任何单个参数重载,但我会从它开始。您还使用列更新月份变量吗?编辑:抱歉应该添加link
  • 尝试df_final['Date'] + pd.DateOffset(Month=df_final['Month']) 用于日期时间操作数,您需要使用适当的函数.replace 用于字符串。

标签: python pandas datetime typeerror


【解决方案1】:

df_final 的一个小例子会被欣赏,但是错误很明显 df_final["Date"] 是一个系列,即数据框中的一列值,而 current_day 是一个整数。 我想你需要的是申请https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html

您将 datettime 对象的每个值替换为月份列。

df_final.apply(lambda row: row["Date"].replace(month=row["Month"])) 可能会起作用,但可能会给出带有复制问题的设置。而且它也可能会很慢,具体取决于您的 df 的大小。

【讨论】:

    猜你喜欢
    • 2021-07-29
    • 1970-01-01
    • 2019-08-11
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多