Home > Back-end >  Select values in two arrays
Select values in two arrays

Time:11-04

I have two arrays of temperature with different times!

x = array(['1999-03-06T12:00:00.000000000', '1999-03-07T12:00:00.000000000',
   '1999-03-08T12:00:00.000000000', ..., '2021-10-09T12:00:00.000000000',
   '2021-10-10T12:00:00.000000000', '2021-10-11T12:00:00.000000000'],
  dtype='datetime64[ns]')

This one is daily from 1999 to 2021

y = array(['2002-07-22T09:03:54.000000000', '2004-11-03T12:36:57.000000000',
   '2004-11-04T05:19:08.000000000', '2004-12-13T11:50:36.000000000',
   '2005-06-07T13:16:41.000000000', '2006-07-12T12:31:53.000000000',
   '2006-07-22T11:43:24.000000000', '2006-09-10T14:08:57.000000000',...]

This one is random from 2002 to 2021

I would like to know how can I select in x (daily) just the dates that contain in y (So x and y will have the same dates)

CodePudding user response:

You can try intersect1d method in numpy.

import numpy as np
array_common_dates = np.intersect1d(x, y)

CodePudding user response:

For larger arrays, sorted lookup will be faster than linear lookup:

# if x is not sorted, fix it
ind = np.searchsorted(x, y)
mask = ind < x.size
mask[mask] &= y[mask] == x[ind[mask]]

The other advantage of this method is that it provides you with a two-way mapping only marked elements match:

y[mask] == x[ind[mask]]

CodePudding user response:

Maybe you can do something like this

x = ['1999-03-06T12:00:00.000000000', '1999-03-07T12:00:00.000000000',
   '1999-03-08T12:00:00.000000000', '2021-10-09T12:00:00.000000000',
   '2021-10-10T12:00:00.000000000', '2021-10-11T12:00:00.000000000']
y = ['1999-03-06T12:00:00.000000001', '1999-03-07T12:00:00.00000004',
   '1999-03-08T12:00:00.000000002', '2021-10-09T12:00:00.000001004',
   '2021-10-10T12:00:00.000000003', '2021-10-11T12:00:00.000002004']
z = []
for i in x:
    n = i.find('T')
    z.append(i[:n])
new_list = []
for i in z:
    for j in y:
        if i in j:
            new_list.append(j)
print(new_list)
  • Related