-2

I am trying to define a function which can fill zero in all the Nan values for all the columns of the input dataframe.

The function takes 1 fixed argument (dataframe name) and variable number of arguments for column names in the dataframe.

I am using below code -

def makeNa(df,*colnames):
    for col in colnames:
        return df.fillna({col:0},inplace=True)

The function works when I pass only one column name e.g. makeNa(df_test,'USA') -it makes all the Nan values as zero for column 'USA' but the function doesn't work while inputting more than one column names e.g. makeNa(df_test,'USA','Japan') --> it doesnt zero the Nan values in column 'Japan'

piyush bansal
  • 39
  • 1
  • 1
  • 7
  • 3
    What are you expecting to happen with Japan, given that you return for USA? – jonrsharpe Aug 05 '19 at 13:41
  • Possible duplicate of [Can a variable number of arguments be passed to a function?](https://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function) – Magnus Reftel Aug 05 '19 at 13:42
  • You should write your question more carefully. No indentation in a python code - especially when defining a function - is usually a bad sign. – Charles Aug 05 '19 at 13:45
  • What do you mean "it doesn't work"? What specifically happens? – clubby789 Aug 05 '19 at 13:46
  • You have an unconditional `return` statement in a `for` loop; the loop will only iterate once. – chepner Aug 05 '19 at 13:46
  • @MagnusReftel - No, it is not entirely the duplication. My query is variable argument function to make the Nan value zero.I corrected the title to avoid confusion – piyush bansal Aug 06 '19 at 06:50
  • @JammyDodger thanks for point it out. I have corrected it – piyush bansal Aug 06 '19 at 06:51

2 Answers2

2

You don't let the loop end, you return at the first iteration. You could do something like:

def makeNa(df, *colnames):
    df[colnames] = df[colnames].filna(0)
    return df
josoler
  • 1,393
  • 9
  • 15
1
def makeNa(df,*colnames):
    for col in colnames:
        df.fillna({col:0},inplace=True)
    return df

you are returning in for loop , instead try to return outside.

Jainil Patel
  • 1,284
  • 7
  • 16