4

This may be a silly question, but I've just started using numpy and I have to figure out how to perform some simple operations.

Suppose that I have the 2x3 array

array([[1, 3, 5],
   [2, 4, 6]])

And that I want to perform some operation on the first column, for example subtract 1 to all the elements to get

array([[0, 3, 5],
   [1, 4, 6]])

How can I perform such an operation?

1

1 Answer 1

10
arr
# array([[1, 3, 5],
#        [2, 4, 6]])

arr[:,0] = arr[:,0] - 1     # choose the first column here, subtract one and 
                            # assign it back to the same column

arr
# array([[0, 3, 5],
#        [1, 4, 6]])
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent answer. I have searched high and low and only found the correct syntax here. I simply needed to know how to do np.mean(dat[:,5]) after using genfromtxt to read a csv file into a numpy array. You wouldn't think that was so far off the beaten path. But you nailed it for me. Thank you very much
And actually, I am going to go back to csv.read() so I can preserve my index values which are a date and a time and show up as nan in genfromtxt, now that I know how this works. This is a great solution. Thank goodness for Google leading me here. And thank you for this answer being here to find. I have to laugh, seeing all the related Q's that Google could have found first. It works in mysterious ways.

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.