Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I created 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]

Thanks

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

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
share|improve this answer
add comment

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 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]])     
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.