Tôi cần khớp hai mảng Numpy rất lớn (một là 20000 hàng, một hàng khoảng 100000 hàng) và tôi đang cố gắng xây dựng tập lệnh để thực hiện hiệu quả. Looping đơn giản trên mảng là cực kỳ chậm, ai đó có thể đề xuất một cách tốt hơn? Dưới đây là những gì tôi đang cố gắng làm: mảng datesSecondDict
và mảng pwfs2Dates
chứa giá trị datetime, tôi cần lấy từng giá trị datetime từ mảng pwfs2Dates
(mảng nhỏ hơn) và xem liệu có giá trị datetime như thế (cộng trừ 5 phút) trong mảng hay không datesSecondDict
(có thể có nhiều hơn 1). Nếu có một (hoặc nhiều hơn) tôi điền một mảng mới (có cùng kích thước với mảng pwfs2Dates
) với giá trị (một trong các giá trị) từ mảng valsSecondDict
(chỉ là mảng có các giá trị số tương ứng là datesSecondDict
). Dưới đây là một giải pháp bởi @unutbu và @joaquin mà làm việc cho tôi (nhờ chàng trai!):Kết hợp điều kiện mảng 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
Cảm ơn, Aina.
cảm ơn rất nhiều, nó hoàn toàn làm việc! – Aina