I have a list of strings, each of which is a complex number. The format is as below:
lr=['3.123+2.43i','0.23454-1.2134i','0.6543+0.76543i','1.12324+0.6543i']
What I want is a list of the modulus of each complex number.
Python natively supports complex numbers, but it uses the engineering convention of j for the imaginary unit instead of the mathematician's i.
lr = ['3+4i', '3.123+2.43i', '0.23454-1.2134i', '0.6543+0.76543i', '1.12324+0.6543i']
for s in lr:
s = s.replace('i', 'j')
v = complex(s)
print(v, abs(v))
output
(3+4j) 5.0
(3.123+2.43j) 3.9570227444380457
(0.23454-1.2134j) 1.2358594465391282
(0.6543+0.76543j) 1.006971486637035
(1.12324+0.6543j) 1.2999140693138143
We can create a list of the moduli using a list comprehension:
moduli = [abs(complex(s.replace('i', 'j'))) for s in lr]
print(moduli)
output
[5.0, 3.9570227444380457, 1.2358594465391282, 1.006971486637035, 1.2999140693138143]
Here's a variation on the 'replace i with j' solution:
In [182]: lr=['3.123+2.43i','0.23454-1.2134i','0.6543+0.76543i','1.12324+0.6543i']
Can make an array of strings:
In [183]: np.array(lr)
Out[183]:
array(['3.123+2.43i', '0.23454-1.2134i', '0.6543+0.76543i',
'1.12324+0.6543i'],
dtype='<U15')
but not complex - at least not directly
In [184]: np.array(lr,np.complex)
...
TypeError: a float is required
but there is a function that performs string replace on array elements:
In [185]: a=np.array(lr)
In [186]: np.char.replace(a,'i','j')
Out[186]:
array(['3.123+2.43j', '0.23454-1.2134j', '0.6543+0.76543j',
'1.12324+0.6543j'],
dtype='<U15')
Now that array of strings can be cast as complex
In [187]: np.char.replace(a,'i','j').astype(np.complex)
Out[187]:
array([ 3.12300+2.43j , 0.23454-1.2134j , 0.65430+0.76543j,
1.12324+0.6543j ])
TypeError: must be real number, not numpy.str_.TypeError: must be real number, not numpy.str_ will be obtained when running np.char.replace(a,'i','j').astype(np.complex).a looks like, so can't help.np.char.replace(a,'i','j') before I can suggest any fixes.