Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I'd like to replace bad values in a column of a dataframe by NaN's.

mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']}

df = pd.DataFrame(mydata)

df[df.y == 'N/A']['y'] = np.nan

Though, the last line fails and throws a warning because it's working on a copy of df. So, what's the correct way to handle this? I've seen many solutions with iloc or ix but here, I need to use a boolean condition.

1 Answer

0 votes
by (41.4k points)

Use replace which will replace bad values in a column of a dataframe by NaN's:

df.replace('N/A',np.NaN)

Output

    x    y

0  10   12

1  50   11

2  18  NaN

3  32   13

4  47   15

5  20  NaN

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...