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.

Let say i have the following:

import numpy as np

data = np.array([
     [1,2,3],
     [1,2,3],
     [1,2,3],
     [4,5,6],         
     ])

How would I go about changing values in column 3 based on values in column 2? For instance, If column 3 == 3, column 2 = 9.

[[1,9,3],
 [1,9,3],
 [1,9,3],
 [4,5,6]]

I've looked at np.any(), but I can't figure out how to alter the array in place.

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

You can use Numpy's slicing and indexing to achieve this. Take all the rows where the third column is 3, and change the second column of each of those rows to 9:

>>> data[data[:, 2] == 3, 1] = 9
>>> data
array([[1, 9, 3],
       [1, 9, 3],
       [1, 9, 3],
       [4, 5, 6]])
share|improve this answer
    
Does this copy the data, or does it alter data in place without reserving additional memory? –  Barbarossa Dec 3 '13 at 18:53
1  
@Barbarossa: It alters the data in place, although additional memory is required to make the index with data[:, 2] == 3. –  mdml Dec 3 '13 at 18:55
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.