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?

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.