Python Pandas:类型错误:+ 不支持的操作数类型:'datetime.time' 和 'Timedelta' [英] Python Pandas: TypeError: unsupported operand type(s) for +: 'datetime.time' and 'Timedelta'

查看:97
本文介绍了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_datetimepd.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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆