【发布时间】:2019-12-23 06:23:43
【问题描述】:
我有一个每小时天气数据集,已导入到 pandas 数据框。在这个数据框中,我有 2 列如下(除了其他列):
wd = pd.read_csv('hourlyweather.csv') # wd is short for Weather Data
wd['Date and Time']= wd['Date and Time'].astype('datetime64[ns]')
wd['Date and Time (int)'] = wd['Date and Time'].astype('int')
wd['Temperature Celsius'] = wd['Temperature Celsius'].astype('double')
我还有另一个数据集(用于每小时车祸),它具有不同的数据但类似的列如下:
cd = pd.read_csv('accidents.csv') # cd is short for Crime Data
cd['Occurred Date Time']= cd['Occurred Date Time'].astype('datetime64[ns]')
cd['Occurred Date Time (int)']= cd['Occurred Date Time'].astype('int')
cd.insert(6,"Temp in Celsius"," ");
我的目标是找出每次车祸的天气温度。由于我没有确切的每小时温度,我想从天气数据集中找到每次事故的最接近温度。因此,对于每次事故,我想从天气数据集中找到最接近的日期和时间,然后获取该日期和时间的温度以将其插入到车祸数据框中的相应列中
我尝试通过 FOR LOOP 来完成它(它工作正常),但它需要很长时间来处理。这是因为我有超过一百万的车祸。以下是我的 FOR 循环:
for i in range((len(cd['Occurred Date Time (int)']))):
sourceint =cd['Occurred Date Time (int)'][i]
idx = wd['Date and Time (int)'].sub(sourceint).abs().idxmin()
cd["Temp in Celsius"][i] = wd['Temperature Celsius'][idx]
没有 FOR LOOP 是否有更有效的方法来执行此操作,这样可以更快地处理这么多的记录?
【问题讨论】:
-
您的 csv 是否已按“日期和时间”排序?
-
@Gepapado 是的,天气(wd)CSV 已经排序。
-
@Gepapado 事故 CSV 按天排序,而不是按小时排序。
-
在 'day' 对两个数据集进行完全左连接会很好。然后为每一行找到两次之间的最小值,然后删除重复项。
-
如果您提供两个数据集的演示数据框,我可以为您提供更多帮助
标签: python pandas dataframe datetime