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.
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.
If you want to replace the '.' in 'col1' only, then you can do:
x.loc[x.col1 == '.', 'col1'] = np.nan
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'])