I am trying to assign complex numbers to an initialized NumPy arrays in the following way
MG = np.zeros((len(Mx), len(My), len(Mz)), dtype=np.complex)
, shape of MG is
print(MG.shape) = (97, 97, 121)
.
I have the data as-
print(data.shape) = (1, 192, 192, 240)
and I take the fft of the data as- CG=np.fft.rfftn(data) print(CG.shape) = (1, 192, 192, 121)
.
The content of CG is also complex number- print(CG[0, 1, 1, 1]) = (-323.8670860547882-348.25820462723163j)
.
I am trying to assign this MG as-
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
where Mxc,Myc,Mzc = np.meshgrid(Mx,My,Mz)
,
with Mx,My, and Mz are numpy arrays of floats.
However, I am getting the following error-
<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
Can anyone please help me with it?
As @Han-KwangNienhuys points out CG
has more dimensions than MG
.
Normally I'd expect such an assignment to produce 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.
But with complex dtype, the error message is different, what you got:
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