1

This thread here shows replace with inplace=True to change values in pandas data frame.

I want to apply the same technique, but replacing with None

mydf = pd.DataFrame({"col1":[5, 5, 8, 4, 5], "col2":[2, 5, 6, 7, 5]})
mydf.replace([5], None, inplace=True)

mydf changes like this and there is an additional output

   col1  col2
0     5     2
1     5     2
2     8     6
3     4     7
4     4     7
col1    None
col2    None
dtype: object

How to replace values with None?

Tristan Tran
  • 1,351
  • 1
  • 10
  • 36

2 Answers2

1

Prefer use pd.NA rather than None. Read this

mydf.replace([5], pd.NA, inplace=True)
# mydf.replace([5], [None], inplace=True)
>>> mydf
   col1  col2
0  <NA>     2
1  <NA>  <NA>
2     8     6
3     4     7
4  <NA>  <NA>
Corralien
  • 109,409
  • 8
  • 28
  • 52
1

None also happens to be the default value for value argument so if you need to use it, you can place it in a 1-element list to distinguish that you're not passing the default:

mydf = mydf.replace([5], [None])

also: inplace=True is not so good, opt for assigning back

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38