Necesito unir dos matrices Numpy muy grandes (una es 20000 filas, otra alrededor de 100000 filas) y estoy tratando de construir una secuencia de comandos para hacerlo de manera eficiente. El simple bucle sobre las matrices es increíblemente lento, ¿alguien puede sugerir una mejor manera? Esto es lo que estoy tratando de hacer: array datesSecondDict
y array pwfs2Dates
contienen valores de fecha y hora, necesito tomar cada valor de datetime del array pwfs2Dates
(matriz más pequeña) y ver si hay un valor de fecha y hora como ese (más menos 5 minutos) en matriz datesSecondDict
(puede haber más de 1). Si hay uno (o más) llenó una nueva matriz (del mismo tamaño que la matriz pwfs2Dates
) con el valor (uno de los valores) de la matriz valsSecondDict
(que es solo la matriz con los valores numéricos correspondientes a datesSecondDict
). Aquí es una solución por @unutbu y @joaquin que trabajó para mí (gracias chicos!):Coincidencia condicional de Numpy array
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
Gracias, Aina.
gracias tanto, es totalmente funcionaba! – Aina