-1

I have to Replace a custom value when a null value is encountered in Numpy array I have come up with something like this but its giving incorrect results.

def func(string, replace_with):
    string[np.where(string == "")] = replace_with
    return string

for

func(np.array(["1","2" ,"", "12", ""]),"100")

its giving

['1' '2' '10' '12' '10'] 

instead of

['1' '2' '100' '12' '100']
sujeet14108
  • 568
  • 5
  • 19

1 Answers1

0

That’s because the datatype of the array you create is "|S2", meaning a string of 2 characters long. Numpy will take your integer value of 100, cast it to a string, to have a similar base data type as the array and then truncate it to 2 characters to fit with the actual array’s dtype.

>>> import numpy as np
>>> a = np.array(["1","2" ,"", "12", ""])
>>> print(a.dtype)
|S2

Side note: you should probably not be using numpy for string manipulations. It’s for number crunching. Consider pandas.

Oliver W.
  • 13,169
  • 3
  • 37
  • 50