Search code examples
pythonpandastype-conversionfillna

Use to_numeric on certain columns only in PANDAS


I have a dataframe with 15 columns. 5 of those columns use numbers but some of the entries are either blanks, or words. I want to convert those to zero.

I am able to convert the entries in one of the column to zero but when I try to do that for multiple columns, I am not able to do it. I tried this for one column:

pd.to_numeric(Tracker_sample['Product1'],errors='coerce').fillna(0)

and it works, but when I try this for multiple columns:

pd.to_numeric(Tracker_sample[['product1','product2','product3','product4','Total']],errors='coerce').fillna(0)

I get the error : arg must be a list, tuple, 1-d array, or Series

I think it is the way I am calling the columns to be fixed. I am new to pandas so any help would be appreciated. Thank you


Solution

  • You can use:

    Tracker_sample[['product1','product2','product3','product4','Total']].apply(pd.to_numeric, errors='coerce').fillna(0)