3d numpy 数组仅沿第 i 列执行操作

3d numpy array perform operation along column i only

我有一个这样的 3d numpy 数组(作为示例)

a = np.array([
        [[1, -2, 3, 4],[5, 6, 7, 8]],
        [[9, 10, 11, 12],[13, 14, 15, 16]]
])

我只想对内部维度中索引为 1 的列中的元素应用以下操作。元素是 [-2,6,10,14] 对于上面的例子。操作将是:

# variables used in the operations
v1, v2, v3 = 12, 4, 2

# the following two operations should only be applied to specified column across all the array

# 1st operation
a[a >= v1] = v1

# output
a = np.array([
        [[1, -2, 3, 4],[5, 6, 7, 8]],
        [[9, 10, 11, 12],[13, 12, 15, 16]]
])

# 2nd operation
f = lambda x: -2 if(x==-2) else (x-v3)/(v2-v3)
a = f(a)

# output

a = np.array([
        [[1, -2, 3, 4],[5, 2, 7, 8]],
        [[9, 4, 11, 12],[13, 5, 15, 16]]
])

有人可以帮助我吗?我研究了几种 NumPy 方法,但似乎无法适应我的示例。

您需要将函数更改为向量函数(即接受一个数组和输入,return 一个数组作为输出),并切片以仅将其应用于所需的“列”:

f = lambda x: np.where(x==-2, -2, (x-v3)/(v2-v3))

a[...,[1]] = f(a[...,[1]])

输出:

array([[[ 1, -2,  3,  4],
        [ 5,  2,  7,  8]],

       [[ 9,  4, 11, 12],
        [13,  5, 15, 16]]])
a = np.array([
        [[1, -2, 3, 4],[5, 6, 7, 8]],
        [[9, 10, 11, 12],[13, 14, 15, 16]]
])

print(a.trasnpose()[1]).reshape(1,4)

将打印:

[[-2 10  6 14]]

a.transpose()[1].flatten()

将打印:

[-2 10  6 14]

你无法对其进行操作