简体   繁体   中英

Fastest way to return adjacent value in numpy array

I have two numpy arrays that hold dates and times. The times on each day don't necessarily match so I need to run through to check to find a match that does.

As such, I have currently created a simple UDF that returns the time of the date passed through. But this take a long time since the arrays are quite large.

Below is my current code, I have broken it down to it's basic principles:

import numpy as np

#my arrays
arr1 = np.array([[20/12/2019, 16:00], [21/12/2019, 12:00], [22/12/2019, 15:00]])
arr2 = np.array([[20/12/2019, 16:00], [21/12/2019, 15:00], [22/12/2019, 16:00]])

#udf
def get_time(index_date):
    for i in range(arr2.shape[0]-1):
        if arr2[i,0] == index_date:
            return arr2[i,1]
            break

#loop through main data
for i in range(arr1.shape[0]-1):
    if arr1[i,1] = get_time(arr1[i,0]):
        print('match')
        break

The above works, but is quite slow and cumbersome. I know there is also something like the below:

if value in my_array[:, col_num]:

But this would not return the adjacent time, it would only check to see if a date exists.

My question:

What is the fastest way to loop through a numpy array to return an adjacent value once an index is found?

This is a workaround and only useful if you can't use Rafael's solution. We replace the date in a temporary array to check which coordinates have a custom value.

You can use

for row in np.array(np.where(np.core.defchararray.replace(p,old="21/12/2019",new="")==''))[0]:
    #Prints time where date == 21/12/2019
    print(p[row,1])

This will find the row coordinate of the target date, and that can get you the next column which in your case is the time. It's trivial to check multiple values, iterating over the values which you want to check and replacing the inner old values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM