# how to use the first 3-digit numpy table strip as imaginary values ​​for all other bands

advertisements

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!

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
```
```