我需要匹配兩個非常大的Numpy數組(一個是20000行,另一個大約100000行),我試圖構建一個腳本來有效地完成它。簡單的循環遍歷數組非常慢,有人可以提出更好的方法嗎?這是我想要做的:數組datesSecondDict
和數組pwfs2Dates
包含日期時間值,我需要從數組pwfs2Dates
(較小的數組)中獲取每個日期時間值,並查看數組中是否有類似的日期時間值(加上減去5分鐘) datesSecondDict
(可能有1個以上)。如果有一個(或多個)I使用數組valsSecondDict
(它只是數字值爲datesSecondDict
的數組)的值(其中一個值)填充新數組(與數組pwfs2Dates
的大小相同)。下面是@unutbu和@joaquin一個解決方案,爲我工作(謝謝你們!):Numpy數組條件匹配
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
感謝, 艾娜。
感謝這麼多,它完全成功了! – Aina 2011-12-20 20:48:33