从xlsx导入持续时间/将对象转换为持续时间

2024-10-03 11:16:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python对大量xlsx文件(所有文件的格式都相同)进行webscrape,并将它们整合到单个文件中,以便使用

In [206]:    
files = glob.glob(path + "/*.xlsx")
df= pd.DataFrame()
df =  pd.concat([pd.read_excel(fp, index_col = 0, header = 3).assign(New=os.path.basename(fp)) for fp in files])
df.dtypes

Out[206]: 
HVR\n>60                                int64
AVG HVR                                 object
Longest HVR                             datetime64[ns]

AVG HVR和最长HVR都是持续时间,但AVG HVR中的某些字段包含毫秒,因此对象中的数据类型如下:

Site           AVG HVR
Leighton       1900-01-01 00:18:30.080000
Macclesfield   1900-01-01 00:23:09

我需要在excel中将这些作为持续时间处理,因此需要将它们转换为timedelta格式,或者以正确的格式从xlsx导入它们

我尝试了下面所有的方法,但都没有用

df['AVG HVG'] = pd.to_timedelta(df['AVG HVG'])
>>> TypeError: Expected unicode, got Timestamp
>>> ValueError: Invalid type for timedelta scalar: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
datetime.combine(date.min, df['AVG HVG']) - datetime.min
>>> TypeError: combine() argument 2 must be datetime.time, not Series
df['AVG HVG'] = df['AVG HVG'] - datetime.time(1900, 1, 1)
>>> TypeError: descriptor 'time' for 'datetime.datetime' objects doesn't apply to a 'int' object
df['AVG HVR'] = df['AVG HVR'].dt.strftime('%H:%M:%S')
>>> KeyError: 'AVG HVR'
df['AVG HVR\n(HH:MM:SS)'] = df['AVG HVR\n(HH:MM:SS)'].astype('|S19')

Tags: 文件dffordatetimetime格式filesxlsx
1条回答
网友
1楼 · 发布于 2024-10-03 11:16:12

背景:Excel将日期存储为序列日期,默认情况下为1900年后的天数。另见:Dates and Times in Excel。但Excel中没有专门的持续时间类型,它们也只是Excel中的日期。因此,在导入到pandas数据帧时,您将得到datetime,而不是timedelta

Datetime到Timedelta:不尝试强制转换到Timedelta(未定义为Datetime->;Timedelta),只需从Datetime列中减去参考日期即可获得Timedelta列

Ex:

import pandas as pd

df = pd.DataFrame({'AVG HVR': [pd.Timestamp("1900-01-01 00:18:30.080000"), 
                               pd.Timestamp("1900-01-01 00:23:09")]})

df['AVG HVR'] = df['AVG HVR'] - pd.Timestamp('1900-01-01')
df['AVG HVR']

0   0 days 00:18:30.080000
1          0 days 00:23:09
Name: AVG HVR, dtype: timedelta64[ns]

相关问题 更多 >