I have a 3d numpy array like [[6,7,8],[1,2,3],[1,2,3]]
and I want to use the first "band" [6,7,8]
as imaginary values for all other "bands". which should looks like that
[[6,7,8],[1+6j,2+7j,3+,8j],[1+6j,2+7j,3+8j]]
anybody know how that works? Thanks for help!
Use all() when you need to check a long series of and conditions. Use any() when you need to check a long series of or conditions.
You can use the np alias to create ndarray of a list using the array() method. The list is passed to the array() method which then returns a NumPy array with the same elements.
Use the hsplit() method to split the 2-D array into three 2-D arrays along rows. Note: Similar alternates to vstack() and dstack() are available as vsplit() and dsplit() .
hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array. Parameters : tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis.
Usually people phrase the "first band" as the first row.
>>> arr = np.array([[6,7,8],[1,2,3],[1,2,3]])
#First need a complex datatype.
>>> arr = arr.astype(np.complex)
>>> arr
array([[ 6.+0.j, 7.+0.j, 8.+0.j],
[ 1.+0.j, 2.+0.j, 3.+0.j],
[ 1.+0.j, 2.+0.j, 3.+0.j]])
# .imag and .real access the real and imaginary parts of the array.
>>> arr[1:].imag = arr[0].real
>>> arr
array([[ 6.+0.j, 7.+0.j, 8.+0.j],
[ 1.+6.j, 2.+7.j, 3.+8.j],
[ 1.+6.j, 2.+7.j, 3.+8.j]])
Skipping multiple casting calls and the vstack can save a fair amount of time:
arr = np.array([[6,7,8],[1,2,3],[1,2,3]])
%timeit a=arr.astype(np.complex);a[1:].imag = a[0].real
100000 loops, best of 3: 4.03 µs per loop
%timeit np.vstack((arr[0,:], arr[1:,:] + arr[0,:] * 1.j))
10000 loops, best of 3: 25.2 µs per loop
For larger arrays:
arr = np.random.rand(500,500)
%timeit a=arr.astype(np.complex);a[1:].imag = a[0].real
1000 loops, best of 3: 898 µs per loop
In [13]: %timeit np.vstack((arr[0,:], arr[1:,:] + arr[0,:] * 1.j))
1000 loops, best of 3: 1.77 ms per loop
The difference mainly comes from the vstack
option having to cast arr to a complex data type twice.
%timeit arr.astype(np.complex)
1000 loops, best of 3: 530 µs per loop
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