如何将复数分配给 numpy 数组

How to assign complex numbers to a numpy array

我正在尝试通过以下方式将复数分配给初始化的 NumPy 数组 MG = np.zeros((len(Mx), len(My), len(Mz)), dtype=np.complex), MG的形状是 print(MG.shape) = (97, 97, 121).

我的数据是- print(data.shape) = (1, 192, 192, 240) 并且我将数据的 fft 取为 - CG=np.fft.rfftn(data) print(CG.shape) = (1, 192, 192, 121)。 CG的内容也是复数- print(CG[0, 1, 1, 1]) = (-323.8670860547882-348.25820462723163j).

我正在尝试将此 MG 分配为-

for i in range(len(Mxc)):
    for j in range(len(Myc)):
        for k in range(len(Mzc)):
            MM = Mxc[i,j,k]**2 + Myc[i,j,k]**2 + Mzc[i,j,k]**2
            if MM < 0.0005:
                MG[i,j,k] = CG[i,j,k]/MM

其中 Mxc,Myc,Mzc = np.meshgrid(Mx,My,Mz), Mx、My 和 Mz 是浮点数的 numpy 数组。

但是,我收到以下错误-

<ipython-input-13-c0f2a935a1dd> in <module>
---> 14                 MG[i,j,k] = CG[i,j,k]/MM
TypeError: only length-1 arrays can be converted to Python scalars

有人可以帮我吗?

正如@Han-KwangNienhuys 指出的那样,CG 的维度比 MG 多。

通常我希望这样的作业产生 sequence error:

In [270]: x = np.ones((3,2)); y = np.zeros((2,3,2))                             
In [271]: x[0,0] = y[0,0]                                                       
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-271-c61c21c08d16> in <module>
----> 1 x[0,0] = y[0,0]

ValueError: setting an array element with a sequence.

但是对于复杂的数据类型,错误信息是不同的,你得到的是:

In [272]: x = np.ones((3,2),complex); y = np.zeros((2,3,2),complex)             
In [273]: x[0,0] = y[0,0]                                                       
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-273-c61c21c08d16> in <module>
----> 1 x[0,0] = y[0,0]

TypeError: only length-1 arrays can be converted to Python scalars