Python中使用pandas时for循环运行速度慢,如何优化代码结构?
性能问题描述
我正在编写的代码整体运行速度尚可,但数据预处理环节性能瓶颈突出。由于数据结构特殊,我目前仅能通过双层for循环遍历实现赋值,该逻辑在DataFrame索引量约7.2万条时运行正常,但若数据量超过该规模,运行速度会大幅下降。
初始实现代码如下:
for j in range(0,len(RWS_a[0][:])): for n in range(0,locN): DF.loc[DF.index[i+n], 'rws'] = RWS_a[n][j] DF.loc[DF.index[i+n], 'azim'] = WT_DIR[j]+angle*(0.5-LOS[j])*2 DF.loc[DF.index[i+n], 'elev'] = -TILT[j] DF.loc[DF.index[i+n], 'range'] = dist[n] DF.loc[DF.index[i+n], 'x'] = dist[n]*np.cos(np.radians(90-(WT_DIR[j]+angle*(0.5-LOS[j])))) DF.loc[DF.index[i+n], 'y'] = dist[n]*np.sin(np.radians(90-(WT_DIR[j]+angle*(0.5-LOS[j])))) DF.loc[DF.index[i+n], 'z'] = 80+dist[n]*np.sin(np.radians(-TILT[j])) i = i+locN
优化方案与效果
2021年7月30日更新:
使用np.tile、np.repeat等NumPy向量化操作的运行速度远高于循环遍历,将索引遍历for循环替换为NumPy操作后,程序运行效率提升了100倍以上。建议同样受for循环耗时问题困扰的开发者尝试该方案。
优化后代码如下:
DFt = pd.DataFrame() DFt['time'] = ts DFt['rws'] = np.ndarray.flatten(RWS_a, 'F') DFt['azim'] = np.repeat(WT_DIR+angle*(0.5-LOS)*2,m) DFt['elev'] = np.repeat(-TILT,m) DFt['range'] = np.tile(dist,n) DFt['x'] = np.tile(dist,n)*np.repeat(np.cos(np.radians(90-(WT_DIR+angle*(0.5-LOS))))*np.cos(np.radians(-TILT)),m) DFt['y'] = np.tile(dist,n)*np.repeat(np.sin(np.radians(90-(WT_DIR+angle*(0.5-LOS))))*np.cos(np.radians(-TILT)),m) DFt['z'] = z_LiDAR+np.tile(np.array(dist),n)*np.repeat(np.sin(np.radians(-TILT)),m)
内容的提问来源于stack exchange,提问作者Turrini Marco
相关产品推荐
相关产品推荐

