Python Pandas:类型错误:+ 不支持的操作数类型:'datetime.time' 和 'Timedelta'

编程入门 行业动态 更新时间:2024-10-14 12:27:42
本文介绍了Python Pandas:类型错误:+ 不支持的操作数类型:'datetime.time' 和 'Timedelta'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图在 Pandas 的数据框中添加两个系列,第一个系列是从 excel 文件导出的 24 小时时间值(例如 17:30),第二个系列是 Timedelta 中相同长度的系列使用pd.Timedelta"命令从浮点数转换的格式.

I am attempting to add two series in a dataframe in pandas with the first series being a 24-hr time value (e.g. 17:30) exported from an excel file and the second series being a series of the same length in Timedelta format converted from floats with the 'pd.Timedelta' command.

无论日变化如何(例如 22:00 + 4 小时 = 02:00),所需的第三列都是 24 小时时间.

The desired resulting third column would be a 24-hr time regardless of day change (e.g. 22:00 + 4 hours = 02:00).

我像这样创建了 Delta 系列:

I created the Delta series like this:

delta = pd.Series(0 for x in range(0, len(df.Time_In_Hours))) for j in range(0, len(df.Time_In_Hours)): delta[j] = pd.Timedelta(df.Time_In_Hours[j], 'h') df = df.assign(Delta = delta) print ("Delta dtype = %s" % (df.Delta.dtype)) print ("Start_Time dtype = %s" % (df.Start_Time.dtype)) #Output Delta dtype = object Start_Time dtype = object

我的目标是:

df["end_Time"] = df["Start_Time"] + df["Delta"]

我收到的错误是:类型错误:+ 不支持的操作数类型:'datetime.time' 和 'Timedelta'

似乎这种 datetime.time 格式是不可变的.我错过了什么吗?

It seems this datetime.time format is immutable. Am I missing something?

推荐答案

原因

错误很明显.如果您检查元素的类型,您会发现在某些时候您要添加datetime.time 对象和pandas.Timedelta.

有两种日期、时间和时间增量:

There are 2 kinds of dates, times and timedeltas:

  • python 内置于 datetime 模块,即 datetime.time, datetime.date, datetime.timedelta, ...
  • pandas/numpy 即 pandas.Timestamp, pandas.Timedelta
  • python's builtin from datetime module i.e. datetime.time, datetime.date, datetime.timedelta, ...
  • pandas / numpy i.e pandas.Timestamp, pandas.Timedelta

这两个堆栈对于加法或比较等基本操作是不兼容的.

these two stacks are incompatible for basic operations as addition or comparison.

将所有内容转换为pandas类型并最终提取时间

Convert everything to pandas type and extract the times in the end

您应该确保列的 dtypes 类似于 datetime64[ns] 和 timedelta64[ns].为此,尝试使用 pd.to_datetime 和 pd.to_timedelta 显式转换它们.

You should make sure, that dtypes of your columns are something like datetime64[ns] and timedelta64[ns]. For that, try converting them explicitly using pd.to_datetime and pd.to_timedelta.

另一种方法是将 Delta 列转换为 datetime.timedelta 您可以尝试

Another approach would be just converting the Delta column to datetime.timedelta you could try

df["end_Time"] = df["Start_Time"] + df["Delta"].map(pd.Timedelta.to_pytimedelta)

但是根据您的 df["Delta"] 和 df["Start_Time"]

更多推荐

Python Pandas:类型错误:+ 不支持的操作数类型:'datetime.time' 和 'Timedelta'

本文发布于:2023-10-28 04:35:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535538.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   不支持   错误   操作   Pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!