1

I have a list of values [1,-1,2,'X']. I want to replace these values that are in the dataframe with a NaN value.

Here is what I tried

non_values = [1,-1,2,'X'] for i in non_values: #azdias is the name of the dataframe that I am trying to change. azdias.replace(i, np.NaN, inplace=True) 

However, the solution above doesn't make change on the output. Is there any other way to do this

1 Answer 1

1

Use DataFrame.mask with default NaNs replace with selected values by DataFrame.isin:

azdias = pd.DataFrame({'a':[1,2,3,-1], 'b':list('XYZX')}) non_values = [1,-1,2,'X'] azdias = azdias.mask(azdias.isin(non_values)) print (azdias) a b 0 NaN NaN 1 NaN Y 2 3.0 Z 3 NaN NaN 

Or use DataFrame.replace:

azdias = azdias.replace(non_values, np.nan) print (azdias) a b 0 NaN NaN 1 NaN Y 2 3.0 Z 3 NaN NaN 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.