How to pass another entire column as argument to pandas fillna() How to pass another entire column as argument to pandas fillna() python python

How to pass another entire column as argument to pandas fillna()


You can provide this column to fillna (see docs), it will use those values on matching indexes to fill:

In [17]: df['Cat1'].fillna(df['Cat2'])Out[17]:0    cat1    dog2    cat3    antName: Cat1, dtype: object


You could do

df.Cat1 = np.where(df.Cat1.isnull(), df.Cat2, df.Cat1)

The overall construct on the RHS uses the ternary pattern from the pandas cookbook (which it pays to read in any case). It's a vector version of a? b: c.


Just use the value parameter instead of method:

In [20]: dfOut[20]:  Cat1      Cat2  Day0  cat     mouse    11  dog  elephant    22  cat     giraf    33  NaN       ant    4In [21]: df.Cat1 = df.Cat1.fillna(value=df.Cat2)In [22]: dfOut[22]:  Cat1      Cat2  Day0  cat     mouse    11  dog  elephant    22  cat     giraf    33  ant       ant    4