python - 更新 numpy 数组的 3 维和 4 维元素

标签 python arrays numpy

我有一个形状为 [12, 8, 5, 5] 的 numpy 数组。我想修改每个元素的第三维和第四维的值。

例如

import numpy as np
x = np.zeros((12, 80, 5, 5))

print(x[0,0,:,:])

输出:

[[ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]]

修改值:

 y = np.ones((5,5))
 x[0,0,:,:] = y
 print(x[0,0,:,:])

输出:

[[ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.]]

我可以使用两个 for 循环修改所有 x[i,j,:,:]。但是,我想知道是否有任何 pythonic 方法可以在不运行两个循环的情况下做到这一点。只是好奇想知道:)

更新

实际用例:

dict_weights = copy.deepcopy(combined_weights)
for i in range(0, len(combined_weights[each_layer][:, 0, 0, 0])):
    for j in range(0, len(combined_weights[each_layer][0, :, 0, 0])):
          # Extract 5x5
          trans_weight = combined_weights[each_layer][i,j]
          trans_weight = np.fliplr(np.flipud(trans_weight ))
          # Update
          dict_weights[each_layer][i, j] = trans_weight

注意:combined_weights 的维度 i、j 可以变化。此列表中有大约 200 个元素,其 i 和 j 维度不同,但第 3 和第 4 维度始终相同(即 5x5)。

我只是想知道是否可以在不运行 2 个 for 循环的情况下使用转置值更新元素组合权重 [:,:,5, 5]。

谢谢。

最佳答案

简单地做-

dict_weights[each_layer] = combined_weights[each_layer][...,::-1,::-1]

关于python - 更新 numpy 数组的 3 维和 4 维元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42345336/

相关文章:

python - pandas 数据帧上的 apply 函数可以生成标量吗?

python - 输入类型 Python Imputer 不支持 Isnan

python - 如何在 Django 模型中保存对象列表?

javascript - 如何读取JSON特定字段并计算并显示

arrays - 在 Perl 中使用 FTP 流中的哈希值

python - 在 Numpy 数组中累积常量值

python - 选择 n 列的每个交替组 - NumPy

python - super() 和@staticmethod 交互

python - 遍历并附加名称列表

c - 将字符分配给 char[x] 会导致段错误