【发布时间】:2011-12-19 17:33:58
【问题描述】:
我需要匹配两个非常大的 Numpy 数组(一个是 20000 行,另一个是大约 100000 行),我正在尝试构建一个脚本来有效地完成它。简单地循环数组非常慢,有人可以提出更好的方法吗?这是我想要做的:数组datesSecondDict和数组pwfs2Dates包含日期时间值,我需要从数组pwfs2Dates(较小的数组)中获取每个日期时间值,看看是否有这样的日期时间值(加上减去 5 分钟)在数组 datesSecondDict 中(可能超过 1 个)。如果有一个(或多个)我用数组valsSecondDict 中的值(其中一个值)填充一个新数组(与数组pwfs2Dates 的大小相同)(这只是具有相应数值的数组) datesSecondDict)。这是@unutbu 和@joaquin 为我提供的解决方案(谢谢大家!):
import time
import datetime as dt
import numpy as np
def combineArs(dict1, dict2):
"""Combine data from 2 dictionaries into a list.
dict1 contains primary data (e.g. seeing parameter).
The function compares each timestamp in dict1 to dict2
to see if there is a matching timestamp record(s)
in dict2 (plus/minus 5 minutes).
==If yes: a list called data gets appended with the
corresponding parameter value from dict2.
(Note that if there are more than 1 record matching,
the first occuring value gets appended to the list).
==If no: a list called data gets appended with 0."""
# Specify the keys to use
pwfs2Key = 'pwfs2:dc:seeing'
dimmKey = 'ws:seeFwhm'
# Create an iterator for primary dict
datesPrimDictIter = iter(dict1[pwfs2Key]['datetimes'])
# Take the first timestamp value in primary dict
nextDatePrimDict = next(datesPrimDictIter)
# Split the second dictionary into lists
datesSecondDict = dict2[dimmKey]['datetime']
valsSecondDict = dict2[dimmKey]['values']
# Define time window
fiveMins = dt.timedelta(minutes = 5)
data = []
#st = time.time()
for i, nextDateSecondDict in enumerate(datesSecondDict):
try:
while nextDatePrimDict < nextDateSecondDict - fiveMins:
# If there is no match: append zero and move on
data.append(0)
nextDatePrimDict = next(datesPrimDictIter)
while nextDatePrimDict < nextDateSecondDict + fiveMins:
# If there is a match: append the value of second dict
data.append(valsSecondDict[i])
nextDatePrimDict = next(datesPrimDictIter)
except StopIteration:
break
data = np.array(data)
#st = time.time() - st
return data
谢谢, 艾娜。
【问题讨论】: