如何将复数放入numpy数组中?

5 投票
3 回答
7000 浏览
提问于 2025-04-18 10:20
>>> 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的数组里,但没有成功。可能是我漏掉了一些基本的东西。

3 个回答

1

我没有足够的声望去评论talonmies的回答(而且建议编辑的队列已经满了),所以我只能把这个放在这里。

np.complex这个东西要被淘汰了,所以你只需要设置 dtype=complex就可以了。

在他们的1.20.0版本更新说明中有关于淘汰的内容:https://numpy.org/doc/stable/release/1.20.0-notes.html?highlight=complex#deprecations

2

你需要把数组的类型转换一下。

举个例子:

>>> 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])
>>> 
10

如果你想创建一个包含复杂值的数组,你需要告诉numpy使用复杂类型:

>>> A = np.zeros((3,3), dtype=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]]

撰写回答