Pandas replacement for items not working

I looked at this issue and most of the questions are about more complicated notes. However, in my case, I have a very simple file frame as a test dummy.

The goal is to replace the string anywhere in the frame with nan, however this does not seem to work (i.e. does not replace, no errors at all). I tried replacing another line, and it doesn't work either. For instance.

d = {'color' : pd.Series(['white', 'blue', 'orange']),
   'second_color': pd.Series(['white', 'black', 'blue']),
   'value' : pd.Series([1., 2., 3.])}
df = pd.DataFrame(d)
df.replace('white', np.nan)

The output is still:

      color second_color  value
  0   white        white      1
  1    blue        black      2
  2  orange         blue      3
+4
source share
2 answers

You need to assign back

df = df.replace('white', np.nan)

or pass param inplace=True:

In [50]:
d = {'color' : pd.Series(['white', 'blue', 'orange']),
   'second_color': pd.Series(['white', 'black', 'blue']),
   'value' : pd.Series([1., 2., 3.])}
df = pd.DataFrame(d)
df.replace('white', np.nan, inplace=True)
df

Out[50]:
    color second_color  value
0     NaN          NaN    1.0
1    blue        black    2.0
2  orange         blue    3.0

Most pandas ops return a copy, and most of them have a parameter inplace, which is usually the defaultFalse

+10

df.replace(), , . df:

df = df.replace('white', np.nan)
df.replace('white', np.nan, inplace = True)
+3

All Articles