for循环中是否存在用于以下操作的简短numpy命令?
import numpy as np
a= np.array([1.0,2.0,3.0,4.0,5.0,6.0])
b= np.array([10.0,20.0,30.0])
c= np.array([100.0,200.0,300.0,900.0])
y=np.linspace(0,2,50)
m=np.array([0.2,0.1,0.3])
A,C,B,Y = np.meshgrid(a,c,b,y,indexing="ij")
print Y
for i in range(0,len(a)):
for j in range(0,len(c)):
for k in range(0,len(b)):
Y[i][j][k]=Y[i][j][k]*m[k]
print "--------"
print Y
摘要来说,我有$ Y_ {ijkl} $,并且我想将$ Y_ {ij0l} $与$ m_0 $相乘,并将$ Y_ {ij1l} $与$ m_1 $相乘,依此类推...
非常感谢!
答案 0 :(得分:2)
要删除循环,只需在这里einsum
。
np.einsum('ijkl,k->ijkl', Y, m)
或者只是广播乘法:
Y * m[:, None]
但是,如果您不想首先创建网状网格,则可以首先广播Y
,以提高存储效率。
np.einsum(
"ijkl,k->ijkl",
np.broadcast_to(y, a.shape + c.shape + b.shape + y.shape),
m,
)
或:
np.broadcast_to(y, a.shape + c.shape + b.shape + y.shape) * m[:, None]
如果您还需要A,C,B,则可以继续使用当前的方法。
性能
In [44]: %%timeit
...: np.einsum(
...: "ijkl,k->ijkl",
...: np.broadcast_to(y, (a.shape[0], c.shape[0], b.shape[0], y.shape[0])),
...: m,
...: )
...:
21.1 µs ± 121 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [45]: %%timeit
...: A,C,B,Y = np.meshgrid(a,c,b,y,indexing="ij")
...: for i in range(0,len(a)):
...: for j in range(0,len(c)):
...: for k in range(0,len(b)):
...: Y[i][j][k]=Y[i][j][k]*m[k]
...:
420 µs ± 1.58 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)