【问题标题】:Select values in two arrays选择两个数组中的值
【发布时间】:2021-11-03 18:55:47
【问题描述】:

我有两个不同时间的温度数组!

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]')

这是从 1999 年到 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',...]

这是从 2002 年到 2021 年的随机事件

我想知道如何在 x 中选择(每天)只是包含在 y 中的日期 (所以 x 和 y 会有相同的日期)

【问题讨论】:

    标签: python arrays numpy date


    【解决方案1】:

    你可以在numpy中尝试intersect1d方法。

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

    【讨论】:

      【解决方案2】:

      对于较大的数组,排序查找将比线性查找更快:

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

      此方法的另一个优点是它为您提供了一种仅标记元素匹配的双向映射:

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

      【讨论】:

        【解决方案3】:

        也许你可以这样做

        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)
        

        【讨论】:

        • OP 有 numpy 数组。虽然您的方法是有效的,但鉴于 numpy 提供的工具,它的效率极低。
        猜你喜欢
        • 1970-01-01
        • 2013-05-26
        • 2022-01-05
        • 2014-12-13
        • 1970-01-01
        • 2019-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多