简体   繁体   中英

Replace list of values in a dataframe with NaN

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

Use DataFrame.mask with default NaN s 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM