【问题标题】:Finding the index of datetime Numpy Python查找 datetime Numpy Python 的索引
【发布时间】:2021-10-29 00:24:45
【问题描述】:

如何编写代码来显示NewdateSetups 中的索引。我想获取每个日期值的索引值,因此对于第一个输出;Newdate 中的'2017-12-22T03:31:00.000000000' 日期值从Setups 开始排在第 6 位,输出将是5。我会怎样能够得到Expected Output

代码:

import numpy as np

Setups= np.array(['2017-09-15T07:11:00.000000000','2017-09-15T11:25:00.000000000',
 '2017-09-15T12:11:00.000000000', '2017-12-22T03:14:00.000000000',
 '2017-12-22T03:26:00.000000000', '2017-12-22T03:31:00.000000000',
 '2017-12-22T03:56:00.000000000'],dtype="datetime64[ns]")

Newdate =  np.array(['2017-09-15T07:11:00.000000000', '2017-12-22T03:31:00.000000000','2017-09-15T11:25:00.000000000', '2017-12-22T03:56:00.000000000'],dtype="datetime64[ns]")

预期输出:

[0, 5, 1, 6]

【问题讨论】:

    标签: python arrays numpy datetime indexing


    【解决方案1】:

    您可以将设置转换为列表并使用index()

    setups_list = list(Setups)
    indices = [setups_list.index(n) for n in Newdate]
    print(indices)
    
    # [0, 5, 1, 6]
    

    【讨论】:

      【解决方案2】:

      您可以使用numpy.isin 获取值的真实性,即值是否常见,然后将其传递给numpy.where,它将为您提供True 值的索引

      >>> np.where(np.isin(Setups, Newdate))
      (array([0, 1, 5, 6], dtype=int64),)
      

      【讨论】:

      • 这将返回 Setups 中存在的项目的位置,但不是按照它们在 Newdate 中给出的顺序。例如,如果您在 Newdate 中有经常性项目,则此解决方案不提供它们的索引
      • @OluwafemiSule,是的,它根据Setups 中的值而不是Newdate 中的值返回位置
      【解决方案3】:

      试试这个:

      list(map(list(Setups).index, Newdate))
      

      输出:

      [0, 5, 1, 6]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-12
        • 2017-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        • 2012-12-01
        • 2013-10-08
        相关资源
        最近更新 更多