Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 281
splinter Avatar asked Nov 13 '17 15:11

splinter


People also ask

How do I fill null values in pandas?

Pandas DataFrame fillna() MethodThe fillna() method replaces the NULL values with a specified value. The fillna() method returns a new DataFrame object unless the inplace parameter is set to True , in that case the fillna() method does the replacing in the original DataFrame instead.

How do you fill a list with null values in Python?

Filling null values You could do this in-place using the isnull() method as a mask, but because it is such a common operation Pandas provides the fillna() method, which returns a copy of the array with the null values replaced.

Does Fillna fill NaN?

The fillna() function is used to fill NA/NaN values using the specified method. The dataframe.


2 Answers

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
like image 111
jezrael Avatar answered Sep 20 '22 19:09

jezrael


You can change to object

ser=ser.astype('object')

Then assign the list np.nan

ser.loc[ser.isnull()]=[[np.nan]]
like image 33
BENY Avatar answered Sep 20 '22 19:09

BENY