goldisfine
goldisfine

Reputation: 4850

How to convert values in a numpy matrix based on a condition?

I'm trying to convert all the values that are zero to one, as referenced in this question. Using the indexing method has no effect on the matrix though.

enter image description here

How would I change all the 0's in my matrix to -1?

Upvotes: 0

Views: 1323

Answers (1)

ali_m
ali_m

Reputation: 74212

Your boolean indexing is failing because new_train_data is currently a matrix of strings (dtype='|S3'), not floating point numbers!

You can cast the matrix to dtype=np.float64 to convert it to floats, then use boolean indexing to assign a value of -1 to all elements that are equal to 0.0:

new_training_data = new_training_data.astype(np.float64)
new_training_data[new_training_data == 0] = -1

Upvotes: 2

Related Questions