0

I have this dataframe:

d = {'col1': [1, 2, "."], 'col2': [3, 4,5]}
x = pd.DataFrame(data=d)
x[x["col1"] == "."]

I want to replace the "." with np.NaN using the third line, but I can't figure out the right code.

Chris
  • 2,019
  • 5
  • 22
  • 67

3 Answers3

1

Just use df.replace():

import numpy as np

x.replace('.',np.nan)

Returns:

   col1  col2
0   1.0     3
1   2.0     4
2   NaN     5

Note that this will replace all occurrences of '.' with NaN in your dataframe.

rahlf23
  • 8,869
  • 4
  • 24
  • 54
1

If you want to replace the '.' in 'col1' only, then you can do:

x.loc[x.col1 == '.', 'col1'] = np.nan
Gerges
  • 6,269
  • 2
  • 22
  • 44
0

call replace on a series rather than entire df

x.col1=x.col1.replace('.',np.nan)

can also use np.where

np.where((x['col1'] == '.'), np.nan,x['col1'])
mad_
  • 8,121
  • 2
  • 25
  • 40