用numpy中的列表中的不同数字划分每个维度



我有形状为(3,3,3(的ndarray和3个数字的列表。

我想用列表中的第一个数字划分第一个维度,用第二个数字划分第二个维度,并用第三个数字划分三维。

示例:

np.random.rand(3,3,3)
>>>array([[[0.90428811, 0.60637664, 0.45090308],
[0.17400851, 0.49163535, 0.62370288],
[0.58701608, 0.91207839, 0.69364496]],
[[0.85290321, 0.85170489, 0.48792597],
[0.02602198, 0.91088298, 0.14882673],
[0.63354821, 0.21764451, 0.30760075]],
[[0.64833375, 0.13583598, 0.50561519],
[0.42832468, 0.91146014, 0.41627495],
[0.71238947, 0.37868578, 0.05874898]]])

和列表:

lst=[0.215, 0.561,0.724]

我希望输出结果是这样的结果:

[0.90428811/0.215, 0.60637664/0.215, 0.45090308/0.215],
[0.17400851/0.215, 0.49163535/0.215, 0.62370288/0.215],
[0.58701608/0.215, 0.91207839/0.215, 0.69364496/0.215]],
[[0.85290321/0.561, 0.85170489/0.561, 0.48792597/0.561],
[0.02602198/0.561, 0.91088298/0.561, 0.14882673/0.561],
[0.63354821/0.561, 0.21764451/0.561, 0.30760075/0.561]],
[[0.64833375/0.724, 0.13583598/0.724, 0.50561519/0.724],
[0.42832468/0.724, 0.91146014/0.724, 0.41627495/0.724],
[0.71238947/0.724, 0.37868578/0.724, 0.05874898/0.724]]])

我试过做这样的事情(arr是ndarray(:

nums=np.arange(3)
for n in nums:
arr[i]=arr[i]/lst[i]

但出现错误:

IndexError:只有整数、切片(:(、省略号(...(,numpy.newaxis(None(和整数或布尔数组是有效的索引

只需执行此操作。它将lst阵列广播为具有易于与a的形状一致的形状(3, 1, 1)

注意,None只是np.newaxis的别名。

import numpy as np
a = np.random.randn(3,3,3)
lst = np.array([0.215, 0.561,0.724])
a / lst[:, None, None]

使用索引广播:

a = np.random.rand(3,3,3)
res = a / lst[:, np.newaxis, np.newaxis]

这之所以有效,是因为lst[:, np.newaxis, np.newaxis]生成了一个形状为(3,1,1(的数组,numpy将大小为1的任何维度扩展到许多常见操作所需的大小(通过重复元素(。这个过程被称为广播。

因此,在我们的例子中,对于除法,lst[:, np.newaxis, np.newaxis]的结果将扩展为:

[[[0.215, 0.215, 0.215],
[0.215, 0.215, 0.215],
[0.215, 0.215, 0.215]],
[[0.561, 0.561, 0.561],
[0.561, 0.561, 0.561],
[0.561, 0.561, 0.561]],
[[0.724, 0.724, 0.724],
[0.724, 0.724, 0.724],
[0.724, 0.724, 0.724]]]

请注意,这种扩展只是在概念上发生的,numpy不会分配更多的内存来一遍又一遍地用相同的值填充它。

这不是一个看起来很好的解决方案(因为lst声明(,但它可以工作:

import numpy as np
np.random.rand(3,3,3)
arr = np.array([[[0.90428811, 0.60637664, 0.45090308],
[0.17400851, 0.49163535, 0.62370288],
[0.58701608, 0.91207839, 0.69364496]],
[[0.85290321, 0.85170489, 0.48792597],
[0.02602198, 0.91088298, 0.14882673],
[0.63354821, 0.21764451, 0.30760075]],
[[0.64833375, 0.13583598, 0.50561519],
[0.42832468, 0.91146014, 0.41627495],
[0.71238947, 0.37868578, 0.05874898]]])

lst = [[[0.215]], [[0.561]],[[0.724]]]
div = np.divide(arr, lst)
print(div)

输出为:

[[[4.20599121 2.82035647 2.09722363]
[0.80934191 2.28667605 2.90094363]
[2.73030735 4.24222507 3.22625563]]
[[1.52032658 1.51819053 0.86974326]
[0.04638499 1.62367733 0.26528829]
[1.12931945 0.38795813 0.54830793]]
[[0.8954886  0.18761876 0.69836352]
[0.59160867 1.25892285 0.5749654 ]
[0.98396336 0.52304666 0.081145  ]]]

最新更新