2

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

user7146708
  • 187
  • 4
  • 12
  • Possible duplicate of [pandas: to\_numeric for multiple columns](https://stackoverflow.com/questions/36814100/pandas-to-numeric-for-multiple-columns) – Toby Petty May 21 '18 at 20:33

2 Answers2

3

You can use:

Tracker_sample[['product1','product2','product3','product4','Total']].apply(pd.to_numeric, errors='coerce').fillna(0)
llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • It did work but I still have issues. I tried to post my code here but there wasn't enough space. I posted a new question: [linkl](https://stackoverflow.com/questions/50457149/modify-some-columns-of-a-dataframe-with-pandas) – user7146708 May 21 '18 at 22:04
  • @user7146708 See jpp's answer in that question, that should solve your problem. – llllllllll May 22 '18 at 03:29
1

With a for loop?

for col in ['product1','product2','product3','product4','Total']:
    Tracker_sample[col] = pd.to_numeric(Tracker_sample[col],errors='coerce').fillna(0)
phi
  • 10,572
  • 3
  • 21
  • 30