0

Say I have a numpy array x:

x = array([[  3,   2,   1],
           [  3,  25,  34],
           [ 33, 333,   3],
           [ 43,  32,   2]])

I want to carry out the following operations without explicitly writing a for loop i.e. say a method which uses automatic in built looping;

1) Replace the 2nd column by a column of all 1 i.e.

x = array([[  3,   1,   1],
           [  3,   1,  34],
           [ 33,   1,   3],
           [ 43,   1,   2]])

2) In the original array , replace 3rd column with the product of 2nd and 3rd i.e.

x = array([[  3,   2,   1*2],
           [  3,  25,  34*25],
           [ 33, 333,   3*333],
           [ 43,  32,   2*32]])

3) Finally, I would like to replace the 2nd column in the original array based on a condition i.e.

x[1] = 0  if x[0] > 5 else 4 

i.e. the array now looks like:

x = array([[  3,   4,   1],
           [  3,   4,  34],
           [ 33,   0,   3],
           [ 43,   0,   2]])

Any suggestions ? Thanks !

2
  • You can do this using a while loop and an iterator variable that is incremented with every loop. May I ask why you can't use a for loop? Commented Jul 23, 2012 at 0:27
  • The array might get very tall, i.e say million elements, which might be repeated 100's of times. Using an explicit for loop is adding a lot of overhead. Therefore, I switched to numpy array in place of lists, hopping that there will be some kind of vectorized solution to this. Commented Jul 23, 2012 at 0:30

1 Answer 1

6

The documentation on numpy is well worth reading as this is fairly basic stuff...

  1. x[:,1] = 1
  2. x[:,2] *= x[:,1]
  3. x[:,1] = np.where( x[:,0] > 5, 0, 4 )
Sign up to request clarification or add additional context in comments.

3 Comments

Jon Clements: Thanks for this ! I was indexing in the wrong way, something like x[:][1] .. Thanks again for this !
Number 2 can be improved by using x[:,2] *= x[:,1] – this saves the creation of a temporary array.
@Sven good point - not sure why I didn't write that - thanks - edited

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.