【发布时间】:2018-10-30 05:50:24
【问题描述】:
- 我正在处理两个 csv 文件并导入为数据框 df1 和 df2
- df1 有 50000 行,df2 有 150000 行。
- 我想比较(遍历每一行)df2 的“时间”与 df1,求时间差并返回所有列的值 对应类似的行,保存在df3中(时间同步)
- 例如,35427949712(df1 中的“时间”)最接近或等于 35427949712(df2中的“时间”),所以我想返回 df1 ('velocity_x' and 'yaw') 和 df2 ('velocity' and 'yawrate') 并保存在 df3 中
- 为此,我使用了两种技术,如代码所示。
- 代码 1 需要很长时间才能执行 72 小时,这不是实践,因为我有很多 csv 文件
- 代码 2 出现“内存错误”并且内核死机。
如果考虑到计算时间、内存和功率(英特尔酷睿 i7-6700HQ,8 GB 内存),如果我能找到一个更强大的解决方案来解决这个问题,那就太好了
这是样本数据,
import pandas as pd
df1 = pd.DataFrame({'time': [35427889701, 35427909854, 35427929709,35427949712, 35428009860],
'velocity_x':[12.5451, 12.5401,12.5351,12.5401,12.5251],
'yaw' : [-0.0787806, -0.0784749, -0.0794889,-0.0795915,-0.0795472]})
df2 = pd.DataFrame({'time': [35427929709, 35427949712, 35427009860,35427029728, 35427049705],
'velocity':[12.6583, 12.6556,12.6556,12.6556,12.6444],
'yawrate' : [-0.0750492, -0.0750492, -0.074351,-0.074351,-0.074351]})
df3 = pd.DataFrame(columns=['time','velocity_x','yaw','velocity','yawrate'])
代码1
for index, row in df1.iterrows():
min=100000
for indexer, rows in df2.iterrows():
if abs(float(row['time'])-float(rows['time']))<min:
min = abs(float(row['time'])-float(rows['time']))
#storing the position
pos = indexer
df3.loc[index,'time'] = df1['time'][pos]
df3.loc[index,'velocity_x'] = df1['velocity_x'][pos]
df3.loc[index,'yaw'] = df1['yaw'][pos]
df3.loc[index,'velocity'] = df2['velocity'][pos]
df3.loc[index,'yawrate'] = df2['yawrate'][pos]
代码2
df1['key'] = 1
df2['key'] = 1
df1.rename(index=str, columns ={'time' : 'time_x'}, inplace=True)
df = df2.merge(df1, on='key', how ='left').reset_index()
df['diff'] = df.apply(lambda x: abs(x['time'] - x['time_x']), axis=1)
df.sort_values(by=['time', 'diff'], inplace=True)
df=df.groupby(['time']).first().reset_index()[['time', 'velocity_x', 'yaw', 'velocity', 'yawrate']]
【问题讨论】:
标签: python python-3.x algorithm pandas data-science