【发布时间】:2017-10-02 15:05:46
【问题描述】:
我有 4 个 numpy 数组:time_start、time_stop、time1、pressure。 对于time_start中的每个元素,我想找到time1中最接近的值的索引,然后读取从那个索引的压力值!
同样,对于time_stop中的每个元素,我想找到time1中最接近的值的索引,然后读取压力值直到那个索引! (time_start 和 time_stop 长度相同)
这是我写的: 查找最近值的函数:
import numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
然后:
p = np.zeros(len(time_start), dtype = object)
itemindex_str = np.zeros(len(time_start), dtype = object)
itemindex_stp = np.zeros(len(time_start), dtype = object)
for i in range(0,len(time_start)):
itemindex_str =np.where(time1==find_nearest(time1,int(time_start[i])))
itemindex_stp = np.where(time1==find_nearest(time1,int(time_stop[i])))
p[i] = pressure[itemindex_str:itemindex_stp]
我得到了错误:
Traceback (most recent call last):
File "re-written_mobility.py", line 174, in <module>
p[i] = pressure[itemindex_str:itemindex_stp]
TypeError: slice indices must be integers or None or have an __index__ method
如果您能帮我解决这个问题,那就太好了。 非常感谢:)
【问题讨论】:
-
首先:为什么不直接返回 idx?
np.where可能返回数组而不是整数,这使得切片有点困难。通过返回idx->itemindex_str = find_nearest(time1, int(time_start[i])))等,可以绕过整个问题。 -
你是对的。现在解决了。非常感谢! :)
-
很高兴能提供帮助,我添加了 quickfix 作为答案。 :)
-
np.where返回一个数组元组,输入的每个维度对应一个数组。在更简单的交互式会话中进行试验。