Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill in missing values in Pandas Dataframe wrong

Suppose 'df' is dataframe object, 'ca' is one of the variables.

>>> df.ca.value_counts()
0.0    176
1.0     65
2.0     38
3.0     20
?        4
Name: ca, dtype: int64

As you can see, I have four missing values. I want to fill in them. Using below code:

>>> df.loc[df.ca == '?', 'ca'] = 0.0
0.0    176
1.0     65
2.0     38
3.0     20
0.0      4
Name: ca, dtype: int64

Why I got 5 unique values? I want to merge fifth row into first row, i.e.

0.0   176 + 4 = 180
1.0     65
2.0     38
3.0     20

How can I fix it?

like image 976
vincent Avatar asked Jul 29 '26 07:07

vincent


1 Answers

Because '?' was one of your values, I know that df.ca is either dtype object or string. When you replace('?', 0.) you now have both string '0.0' and float 0.0. After you convert all to float, you shouldn't have a problem.

df.ca.replace('?', 0.).astype(float).value_counts()

0.0    180
1.0     65
2.0     38
3.0     20
dtype: int64
like image 137
piRSquared Avatar answered Jul 31 '26 20:07

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!