let's say I have a numpy array:
import numpy as np
x = np.array((1 + 2j, 2 + 4j, 5 + 10j))
and I want to create two separate arrays, one of the real component, and one with the complex number component without the j. Is there a shortcut to perform this operation in python? the only way i can think of doing this is explicitly:
xr = np.zero(len(x))
xi = np.zero(len(x))
for n in range(0, len(x)):
xr[m] = x[n].real
xi[m] = x[n].imag
dunno, just seems like there should be a faster way of typing this...
like
xr = x.real?
xi = x.imag?
In [145]: x = np.array((1 + 2j, 2 + 4j, 5 + 10j))
In [146]: x
Out[146]: array([1. +2.j, 2. +4.j, 5.+10.j])
The real and imag attributes work for the whole array just as well as for elements:
In [147]: x.real
Out[147]: array([1., 2., 5.])
In [148]: x.imag
Out[148]: array([ 2., 4., 10.])
In [149]: xr, xc = x.real, x.imag
In [150]: xr
Out[150]: array([1., 2., 5.])
In [151]: xc
Out[151]: array([ 2., 4., 10.])
The view approach that @user3483203 suggests, tells it to interpret the same databuffer as a sequence of two floats:
In [156]: x.view('(2,)float')
Out[156]:
array([[ 1., 2.],
[ 2., 4.],
[ 5., 10.]])
In [157]: np.dtype('(2,)float')
Out[157]: dtype(('<f8', (2,)))
This notation can be obscure unless you've already worked with structured arrays and compound dtypes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With