1

I have a numpy array:

array([[ 0.68597575,  0.05544651, -1.        ],
       [ 0.33494648,  0.46368367,  1.        ],
       [ 0.42486765,  0.89427025,  1.        ],
       [ 0.62408611,  0.64633939,  1.        ],
       [ 0.37087957,  0.53077302, -1.        ],
       [ 0.21664159,  0.10786084, -1.        ],
       [ 0.13003626,  0.18425347, -1.        ]])

I want the rows having last values -1 to be multiplied by -1 and also replaced in the actual matrix.

I tried this:

def transform(data):
    for row in data:
        if row[-1] == -1:
            row = row * -1

but I know there would be something simpler than this.

2 Answers 2

2

You can avoid the for loop by doing:

data[data[:, -1] == -1] *= -1
Sign up to request clarification or add additional context in comments.

Comments

1

i prefer to do this in two steps for two reasons: (i) easier to understand the code; and (ii) often the boolean index created in the first step can be reused elsewhere in the data pipeline

create the Boolean index that selects the rows:

idx = M[:,-1] == -1

do the transform on the indexed data:

M[idx,] *= -1

1 Comment

yep--looks like you posted yours while i was still writing mine, which is consistent with the time diff (~ 3 minutes apart, and in those 3 min i split my answer into two lines and added some comments to make it easier to understand)

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.