import pandas as pd
def hour_timedelta(a):
dt_1 = pd.Timedelta('6 hours')
return a > dt_1
df=pd.read_excel('xinju.xlsx')
df.loc[:, '首次告警时间'] = pd.to_datetime(df.loc[:, '首次告警时间']) # 转换时间类型
df.loc[:, '最后告警时间'] = pd.to_datetime(df.loc[:, '最后告警时间'])
df.insert(8, column='时间差', value=pd.Timedelta('1 hours')) # 插入一个列,作为后面两个时间计算值的承载
i = 0
while i < len(df): # 输出Timedelta的值给到时间差列
df.loc[:, '时间差'].at[i] = df.loc[:, '最后告警时间'].at[i] - df.loc[:, '首次告警时间'].at[i] # 计算出来持续时间
i += 1
dt_1 = df.loc[df['时间差'].apply(hour_timedelta)] #筛选出来时间差大于6小时的
df.to_excel('1.xlsx')
df1=pd.read_excel('1.xlsx')
dt_2 = df1.loc[df1['时间差'].apply(hour_timedelta)]
输出结果:
Traceback (most recent call last):
File "C:\python\learning_pandas\003.py", line 19, in <module>
dt_2 = df1.loc[df1['时间差'].apply(hour_timedelta)]
File "C:\Users\10701\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py", line 4138, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\_libs\lib.pyx", line 2467, in pandas._libs.lib.map_infer
File "C:\python\learning_pandas\003.py", line 6, in hour_timedelta
return a > dt_1
TypeError: '>' not supported between instances of 'float' and 'Timedelta'
时间差那列是Timedelta类,我把他保存到Excel里面,再次读取出来变成了float类,不能再进行比较了
pandas的Timedelta类保存到Excel里面,再次读取出来格式变成了float类型,怎么处理?