Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use first band of 3d numpy array as imaginary values for all other bands

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!

like image 736
g07kore Avatar asked Sep 26 '13 17:09

g07kore


People also ask

How do you use a ANY () or a all ()?

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.

How do you create an alias of an array using NumPy?

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.

How do you split an array into multiple arrays in Python?

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() .

How do I use Hstack in Python?

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.


1 Answers

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
like image 72
Daniel Avatar answered Oct 04 '22 14:10

Daniel