Python / pandas function to replace '-' negative sign but not negative sign in negative numbers ( '-' in '-1')
There is no need for .replace()
at all. Find the cells that contain the dash, and update them:
df[df['Values'] == '-'] = np.nan
Bear in mind that 'NaN'
is not a NaN: it is a string that looks like a NaN. A "real" NaN is np.nan
from numpy.
You can cast the value of the column as numeric. Then maybe -
will be replaces by 0
, not sure if you want it :
pandas.to_numeric(arg, errors='raise', downcast=None)
Reference
If it doesn't work, astype
may be an alternative
DataFrame.astype(dtype, copy=True, errors='raise')
# Example :
df.astype({'values': int})
Reference
Nevertheless the most elegant solution, and the most often used is to use th pandas selector:
df[ df['Values'] == '-' ] = np.nan
Also you can choose to replace the value -
by anything you want: 0
,
Nan
(np.nan), etc.