>>> import numpy as np
>>> A = np.zeros((3,3))
>>> A[0,0] = 9
>>> A
array([[ 9., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> A[0,1] = 1+2j
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
>>> A[0,1] = np.complex(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
根据我的示例代码。我试图将复数放入numpy的数组中,但它不起作用。可能是我想念一些基本的东西。
答案 0 :(得分:7)
如果要创建包含复杂值的数组,则需要指定一个复杂类型为numpy:
>>> A = np.zeros((3,3), dtype=np.complex)
>>> print A
[[ 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j]]
>>> A[0,0] = 1. + 2.j
>>> print A
[[ 1.+2.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j]
[ 0.+0.j 0.+0.j 0.+0.j]]
答案 1 :(得分:1)
您需要转换数组的类型。
示例:强>
>>> from numpy import array, dtype
>>> A = array([1, 2, 3])
>>> A[0] = 1+2j
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to long
>>> B = A.astype(dtype("complex128"))
>>> B[0] = 1+2j
>>> B
array([ 1.+2.j, 2.+0.j, 3.+0.j])
>>>