2

I have defined two arrays:

a=np.array([[2,3,4],[5,6,7],[8,9,10]])
b=np.array([-1,-2])

and created a third one:

x=np.asarray([[x - a/2, x + a/2] for x in b])

Now, I have defined two variables

u,v = x[:,0], x[:,1]

My question is extremely simple: is there a way to define those variables without the comma, using only array operations? If I write

 u,v = x[:,]

the ordering comes out wrong.

QuantumBrick
  • 249
  • 1
  • 8
  • Are you looking for `u, v = x.T`? – Mateen Ulhaq Feb 15 '19 at 01:56
  • 1
    Possible duplicate of [Unpack NumPy array by column](https://stackoverflow.com/questions/27046533/unpack-numpy-array-by-column) – Mateen Ulhaq Feb 15 '19 at 01:56
  • Not really. I want exactly the ``u`` and ``v`` that come from ``u,v = x[:,0], x[:,1]``, but was wondering if there's no way to write this compactly. – QuantumBrick Feb 15 '19 at 01:59
  • I know this is possible with ``u,v = np.hsplit(x,x.shape[1])`` or just a ``for`` loop, but it's weird that there's no manipulation of ``:`` and ``,`` that doesn't do this. – QuantumBrick Feb 15 '19 at 02:01
  • If I run this correctly in my head, `x` is (2,2,3,3) shape. `u` is (2,3,3), selecting on axis 1. `x[:,]` is just `x`. Unpacking just iterates on first axis. You'd have to swap axes to unpack on the 2nd - i.e. move 2nd to 1st. – hpaulj Feb 15 '19 at 02:03
  • Unpacking is a basic Python operation, essentially iterating on the object - such as a tuple or list. Simple iteration on an array is along the first, outermost, axis. – hpaulj Feb 15 '19 at 04:29

1 Answers1

2

If x is 2D:

u, v = x.T

If x is ND:

u, v = np.swapaxes(x, 0, 1)

To confirm:

>>> np.all(u == x[:, 0])
True

>>> np.all(v == x[:, 1])
True
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135