如何优化Pandas中Epoch时间转Datetime代码执行过慢的问题
问题描述
可复现的测试数据集代码如下:
import numpy as np import pandas as pd np.random.seed(365) rows = 17000 data = np.random.uniform(20.25, 23.625, size=(rows, 1)) df = pd.DataFrame(data , columns=['Ta']) # 设置时间索引 Epoch_Start=1636757999 Epoch_End=1636844395 time = np.arange(Epoch_Start,Epoch_End,5) df['Epoch']=pd.DataFrame(time) df.reset_index(drop=True, inplace=True) df=df.set_index('Epoch')
需求如下:
- 新增一列将Epoch时间转换为Datetime格式的
dates列,示例格式:2021-11-12 22:59:59 - 后续需要使用
groupby按指定小时求均值,当前使用的逐行循环代码耗时过长,需要优化运行效率
现有耗时代码
import time def obt_dat(path): df2=df df2['date'] = df.index.values df2['date'] = pd.to_datetime(df2['date'],unit='s') df2['hour']='' df2['fecha']='' df2['dates']='' start = time.time() for i in range(0,len(df2)): df2['hour'].iloc[i]=df2['date'].iloc[i].hour df2['fecha'].iloc[i]=str(df2['date'].iloc[i].year)+str(df2['date'].iloc[i].month)+str(df2['date'].iloc[i].day) df2['dates'] = df2['fecha'].astype(str) + df2['hour'].astype(str) end = time.time() T=round((end-start)/60,2) print('Tiempo de Ejecución Total: ' + str(T) + ' minutos') return(df2) obt_dat(df)
优化方案
代码运行慢的核心原因是使用了逐行循环操作,pandas内置的向量化运算效率远高于手动循环,优化后17000行数据的运算耗时可以从分钟级降到毫秒级。
优化后的代码如下:
import time import pandas as pd def obt_dat(df): start = time.time() # 直接将Epoch索引转为要求的Datetime格式dates列 df['dates'] = pd.to_datetime(df.index, unit='s') # 向量化提取小时列 df['hour'] = df['dates'].dt.hour # 向量化生成年月日拼接的fecha列 df['fecha'] = df['dates'].dt.strftime('%Y%m%d') # 如果你需要保留原代码中年月日+小时拼接的字符串列,可取消注释下一行 # df['date_str'] = df['dates'].dt.strftime('%Y%m%d%H') end = time.time() T = round((end - start), 4) print(f'Tiempo de Ejecución Total: {T} 秒') return df # 调用函数 df = obt_dat(df)
如果后续仅需要按小时分组求均值,甚至不需要创建任何中间列,直接一行代码即可完成需求:
# 按小时分组计算Ta的均值 hourly_ta_mean = df.groupby(pd.to_datetime(df.index, unit='s').floor('H'))['Ta'].mean()
内容的提问来源于stack exchange,提问作者IV__95
相关产品推荐
相关产品推荐

