简体   繁体   English

使用索引作为参数沿 numpy 数组应用 function

[英]Applying a function along a numpy array using indexes as parameters

I am trying to find a way to run a function through a whole ndarray using the indexes of every value as parameters.我试图找到一种方法来使用每个值的索引作为参数通过整个 ndarray 运行 function。 A regular loop is quite slow and I can't find a way to make it work using numpy built-in functions.常规循环非常慢,我找不到使用 numpy 内置函数使其工作的方法。 The next example code summarizes what i'm trying to do.下一个示例代码总结了我正在尝试做的事情。 Thanks in advance.提前致谢。

import numpy as np

arr = np.arange(10).reshape(2, 5)

print(arr)

def example_func(row, col, value):
    return(row + col + value)

for row in range(arr.shape[0]):
    for col in range(arr.shape[1]):
        arr[row, col] = example_func(row, col, arr[row, col])

print(arr)
[[0 1 2 3 4]
 [5 6 7 8 9]]

[[ 0  2  4  6  8]
 [ 6  8 10 12 14]]

What you try to do can be done with meshgrid .您尝试做的事情可以用meshgrid来完成。

Return coordinate matrices from coordinate vectors.从坐标向量返回坐标矩阵。

n_rows, n_cols = arr.shape
col_matrix, row_matrix = np.meshgrid(np.arange(n_cols), np.arange(n_rows))
result = arr + col_matrix + row_matrix
print(result)

This returns这返回

[[ 0  2  4  6  8]
 [ 6  8 10 12 14]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM