Python Forum

Full Version: Replace ? by 0
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello to everyone,

I have a panda dataframe with many columns, one of them contains the ages of clients but when the age is unknown, I have ?. I'd like to replace the ? by 0. In index 15, the age is unknown.

test.fillna(value={"age": 0}).age.head(16)
test is the name of my dataframe and i'm displaying the first seventeenth values, i don't have an error message but nothing changes and ? is still in index 15. Do you know why?
Hi matador,

Try this, if '?' represents NaN Values,

test=test.fillna('0')
Or

test = test.fillna('0')
One of those lines of Code, should replace NaN values to '0'

I hope that works for you ))

Regards

Eddie Winch
Hi eddywinch82,

Thanks for your reply but the problem is that i donn't have NaN values but ? (question mark).

Your line of code don't make any change.
I see matador,

Try the following, sorry if it doesn't work :-

test['age'] = test['age'].replace({'?': '0'})
Regards

Eddie Winch
That works very well.

Thank you very much :)
My pleasure matador,

I am really pleased it worked for you,

I am glad to help.

Best Regards

Eddie Winch Smile
Hi again Matador,

The Code I gave you, will change all '?' in the 'age' Column.

But I realised there is a shorter way, to get the change you wanted.

You said you wanted to change, the '?' in the 'age' Column at Index 15 to '0'

So using .loc you can change, the '?' to '0' at that specific Row and Index, and not change other '?' in the other Rows, in the 'age' Column if they were present.

Therefore using the following Line of Code, should also work :-

test.loc[15,'age']='0'
Could you let me know, if that also works for you ?

Best Regards

Eddie Winch Smile