快速遍历numpy数组的numpy数组的方法

时间:2019-08-14 12:37:56

标签: python numpy

我有一个numpy数组的numpy数组,例如以下示例:

data = [[0.4, 1.5, 2.6],
        [3.4, 0.2, 0.0],
        [null, 3.2, 1.0],
        [1.0, 4.6, null]]

如果值满足条件,我想返回行索引,列索引和值的有效方法。

我需要行和列的值,因为我将它们输入到func_which_returns_lat_long_based_on_row_and_column(column, row)中,如果值满足条件,则会应用该值。

最后,我想将值和函数输出附加到my_list

我使用下面显示的嵌套for循环解决方案解决了我的问题,但是它很慢。我相信我应该使用np.where(),但我无法弄清楚。

my_list = []
for ii, array in enumerate(data):
    for jj, value in enumerate(array):
        if value > 1:
            lon , lat = func_which_returns_lat_long_based_on_row_and_column(jj,ii)
            my_list.append([value, lon, lat])

我希望有一种比上面使用的解决方案更有效的解决方案。

3 个答案:

答案 0 :(得分:2)

import numpy as np
import warnings
warnings.filterwarnings('ignore')
data = [[0.4, 1.5, 2.6],
        [3.4, 0.2, 0.0],
        [np.nan, 3.2, 1.0],
        [1.0, 4.6, np.nan]]
x = np.array(data) 
i, j = np.where(x > 1 )
for a, b in zip(i, j):
    print('lon: {} lat: {} value: {}'.format(a, b, x[a,b]))

输出为

lon: 0 lat: 1 value: 1.5
lon: 0 lat: 2 value: 2.6
lon: 1 lat: 0 value: 3.4
lon: 2 lat: 1 value: 3.2
lon: 3 lat: 1 value: 4.6

由于相比之下有np.nan,因此会有RuntimeWarning

答案 1 :(得分:0)

您可以使用

result = np.where(arr == 15)

它将返回np个索引数组,其中元素位于arr中

答案 2 :(得分:0)

尝试构建对数组有效的函数。例如,将对应的列和行索引添加到数据的每个元素的函数可能看起来像这样:

import numpy as np

def func_which_returns_lat_long_based_on_row_and_column(data,indices):
    # returns element of data + columna and row index
    return data + indices[:,:,0] + indices[:,:,1]

data = np.array([[0.4, 1.5, 2.6],
                 [3.4, 0.2, 0.0],
                 [np.NaN, 3.2, 1.0],
                 [1.0, 4.6, np.NaN]])

# create a matrix of the same shape as data (plus an additional dim because they are two indices)
# with the corresponding indices of the element in it
x_range = np.arange(0,data.shape[0])
y_range = np.arange(0,data.shape[1])
grid = np.meshgrid(x_range,y_range, indexing = 'ij')
indice_matrix = np.concatenate((grid[0][:,:,None],grid[1][:,:,None]),axis=2)

# for instance:
# indice_matrix[0,0] = np.array([0,0])
# indice_matrix[1,0] = np.array([1,0])
# indice_matrix[1,3] = np.array([1,3])

# calculate the output 
out = func_which_returns_lat_long_based_on_row_and_column(data,indice_matrix)
data.shape
>> (4,3)

indice_matrix.shape
>> (4, 3, 2)
indice_matrix 
>>> array([[[0, 0],
        [0, 1],
        [0, 2]],

       [[1, 0],
        [1, 1],
        [1, 2]],

       [[2, 0],
        [2, 1],
        [2, 2]],

       [[3, 0],
        [3, 1],
        [3, 2]]])
indice_matrix[2,1]
>> array([2, 1])