0

Replacing negative numbers to zero is straightforward, see How to replace negative numbers in Pandas Data Frame by zero but I want to know how to do the opposite.

I want to replace the 0 here to -1:

enter image description here

But df.replace(0,-1) or df[df == 0] = -1 gives me

enter image description here

It seems like I am able to replace the zeros into positive integers but I cannot replace them with negative integers (i.e. df.replace(0,-3) replaces all my zeros with -253).

Am I missing something here?

noiivice
  • 400
  • 2
  • 15

1 Answers1

3

I believe you have a data type of 8 bit unsigned integer. For that data type, there are no negatives and therefore a -1 overflows(underflows?) to the largest such number.

df = pd.DataFrame([[0, 1], [1, 0]], dtype=np.uint8)

df.replace(0, -1)

     0    1
0  255    1
1    1  255

Where 255 is the largest such number.

np.iinfo(np.uint8).max

255

Instead, set the data type first

df.astype(int).replace(0, -1)

   0  1
0 -1  1
1  1 -1
piRSquared
  • 285,575
  • 57
  • 475
  • 624