1

Suppose I have a numpy array:

[[2, 1, 1, 1],
 [0, 2, 1, 1],
 [0, 0, 2, 1]]

How do I change all of the twos to be ones?

[[1, 1, 1, 1],
 [0, 1, 1, 1],
 [0, 0, 1, 1]]

There are naive ways to do it that are really slow (i.e. looping through every entry). I have to do it on a large dataset, so a fast solution is essential.

Jacob Stern
  • 3,758
  • 3
  • 32
  • 54
  • if memory and speed is a concern, you may consider using [`numexpr`](https://github.com/pydata/numexpr), which gives you a good tradeoff for using `numpy` vectorized operations in memory efficient [*and often faster* way](https://numexpr.readthedocs.io/en/latest/intro.html). – juanpa.arrivillaga Aug 14 '19 at 21:04

1 Answers1

1

I was able to do this quickly enough using a mask:

x[x == 2] = 1

You can also apply more complicated masks (with bitwise python operators) if you have other numbers that you want to convert to ones:

x[(x == 2) | (x == 3)] = 1
Jacob Stern
  • 3,758
  • 3
  • 32
  • 54