Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas fill cells with NaN when conditions are met

import pandas as pd
import numpy as np
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
df[df['c'] == 3]['a'] = np.nan
df
>>>
    a   b   c
0   1   2   3
1   4   5   6

Why is 0,a not NaN? I would expect that the value in 0,a would have been replaced by np.nan.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Problem is you create chained indexing:

df[df['c'] == 3]

with:

df[df['c'] == 3]['a']

So after set values is not propagate new value to original DataFrame.

For avoid it use DataFrame.loc:

df.loc[df['c'] == 3, 'a'] = np.nan
print (df)
     a  b  c
0  NaN  2  3
1  4.0  5  6

More information.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading