Convert" -" used for empty columns in a dataframe to 0 without changing the negative values?

Viewed 208

I have a column in a dataframe that looks like this

Index Col
0     -1
1      2
2     -3
3      -
4      3
5     - 
6     -7 

how do i replace the "-" used to represent null values in the Col(like at index 3 and 5) to 0 without changing the minus sign in front of the negative values to zero. current dtype is object and i plan to change it to a float after handling the null values.

3 Answers

You can use replace like this:

df.replace('-', 0).astype(float)

Output:

       Col
Index     
0     -1.0
1      2.0
2     -3.0
3      0.0
4      3.0
5      0.0
6     -7.0

Try this

df[df.Col.eq('-')] = 0
print(df)

Output:

  Col
0  -1
1   2
2  -3
3   0
4   3
5   0
6  -7

You could simply use

df["Col"] = df.Col.str.replace('^-$', '0')
print(df)
Related