Search code examples
python-3.xpandasseriesmissing-datafillna

Filling nulls with a list in Pandas using fillna


Given a pd.Series, I would like to replace null values with a list. That is, given:

import numpy as np
import pandas as pd
ser = pd.Series([0,1,np.nan])

I want a function that would return

0        0
1        1
2    [nan]

But if I try using the natural function for this, namely fillna:

result = ser.fillna([np.nan])

but I get the error

TypeError: "value" parameter must be a scalar or dict, but you passed a "list"

Any suggestions of a simple way to acheive this?


Solution

  • Use apply, because fillna working with scalars only:

    print (ser.apply(lambda x: [np.nan] if pd.isnull(x) else x))
    0        0
    1        1
    2    [nan]
    dtype: object