'How do I replace the values of a pandas column without knowing the existing value?

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.



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec
Solution 2