【问题标题】:Numpy slicing and indexingNumpy 切片和索引
【发布时间】: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 返回一个数组元组,输入的每个维度对应一个数组。在更简单的交互式会话中进行试验。

标签: numpy slice


【解决方案1】:

np.where 可能返回数组而不是整数,这使得切片有点困难。通过返回idx 可以绕过整个问题。

def find_nearest(array,value):
    idx = (np.abs(array-value)).argmin()
    return idx
itemindex_str = find_nearest(time1,int(time_start[i]))
itemindex_stp = find_nearest(time1,int(time_stop[i]))

【讨论】:

    【解决方案2】:

    如果我理解你的问题,你想要这个吗?:

    result = [pressure[i] for i in [np.abs(time1 - ts).argmin() for ts in time_start]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多