首页 > 解决方案 > 在 Numpy Array Python 中获取日期时间索引

问题描述

我怎样才能编写一个代码来显示我所在位置的Newdate1 and Newdate2索引SetupsNewdate1within的值Setups是输出1for的第二个索引result。但是该np.where功能不起作用。如果没有 for 循环,我怎么能做到这一点?

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]")
    
Newdate1 =  np.array(['2017-09-15T07:11:00.000000000'], dtype="datetime64[ns]")
Newdate2 =  np.array(['2017-12-22T03:26:00.000000000'], dtype="datetime64[ns]")

result = np.where(Setups == Newdate1)
result2 = np.where(Setups == Newdate2)

预期输出:

result: 1
result2: 4

标签: arrayspython-3.xnumpydatetimeindexing

解决方案


用于np.in1d传递要在另一个数组中搜索的数组并使用np.where.

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

newdates = np.array(['2017-09-15T07:11:00.000000000','2017-12-22T03:26:00.000000000'],dtype="datetime64[ns]")
print(np.where(np.in1d(Setups,newdates)))

输出:

(array([0, 4]),)

推荐阅读