Home > other >  How do I replace the values of a pandas column without knowing the existing value?
How do I replace the values of a pandas column without knowing the existing value?

Time:04-28

I have a pandas dataframe which has randomly generated numbers below. Is there a way of changing the values to 0 of columns 'account', 'number', 'type', 'sun'?

Name account number type sun
Tom 558 787 878 454

I would like to replace these digits with 0.

I tried df['account'] = 0 and df['account'].replace(0), but I think the str.replace method assumes you knowing what you want to replace.

I want to make it so it is a blanket, replacing any value that may be populated there, and it is not relying on knowing what is already present.

CodePudding user response:

You can assign a value to multiple columns at once, like this:

df[['account', 'number', 'type', 'sun']] = 0

Output:

>>> df
  Name  account  number  type  sun
0  Tom        0       0     0    0

CodePudding user response:

Assuming that "it is not relying on knowing what is already present" means you don't know column names, but only want to replace numbers, this method would work:

df.applymap(lambda x: 0 if str(x).isnumeric() else x)

Output:

  Name  account  number  type  sun
0  Tom        0       0     0    0
  • Related