0

I created a NumPy array,

a = numpy.array([[1,2,3][4,5,6]])

I want to make the array look like this [[1,4],[2,5],[3,6]] and also after I make change I want to return to the original structure.

Is there a NumPy command to run a function on all values, like a[0] * 2?

The result should be

[[2,8][2,5][3,6]

2 Answers 2

5

You want to transpose the array (think matrices). Numpy arrays have a method for that:

a = np.array([[1,2,3],[4,5,6]])
b = a.T  # or a.transpose()

But note that b is now a view of a; if you change b, a changes as well (this saves memory and time otherwise spent copying).

You can change the first column of b with

b[0] *= 2

Which gives you the result you want, but a has also changed! If you don't want that, use

b = a.T.copy()

If you do want to change a, note that you can also immediately change the values you want in a itself:

a[:, 0] *= 2
Sign up to request clarification or add additional context in comments.

Comments

1

You can use zip on the ndarray and pass it to numpy.array:

In [36]: a = np.array([[1,2,3], [4,5,6]])

In [37]: b = np.array(zip(*a))

In [38]: b
Out[38]:
array([[1, 4],
       [2, 5],
       [3, 6]])

In [39]: b*2
Out[39]:
array([[ 2,  8],
       [ 4, 10],
       [ 6, 12]])

Use numpy.column_stack for a pure NumPy solution:

In [44]: b = np.column_stack(a)

In [45]: b
Out[45]:
array([[1, 4],
       [2, 5],
       [3, 6]])

In [46]: b*2
Out[46]:
array([[ 2,  8],
       [ 4, 10],
       [ 6, 12]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.