Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use empty list as fill value for Series.fillna

I need to change the NaN values the column 'FocusColumn' to empty lists.


I tried to do it like this:

df['FocusColumn'].fillna([],inplace=True)

But it throws me the following error:

337         if validate_scalar_dict_value and isinstance(value, (list, tuple)):
338             raise TypeError( 
339                 '"value" parameter must be a scalar or dict, but 
340                 f'you passed a "{type(value).__name__}"'
341             )
TypeError: "value" parameter must be a scalar or dict, but you passed a "list"

What is the correct way to do it?

like image 344
Ruben Dario Guarnizo Martinez Avatar asked Oct 14 '25 04:10

Ruben Dario Guarnizo Martinez


1 Answers

Looks like you can work around this by supplying a dict to Series.fillna.

>>> df
   FocusColumn
0          NaN
1          1.0
2          NaN
>>> df['FocusColumn'].fillna({i: [] for i in df.index})
0    []
1     1
2    []
Name: FocusColumn, dtype: object

Notes:

  1. Surprisingly, this only works for Series.fillna.
  2. For large Series with few missing values, this might create an unreasonable amount of throwaway empty lists.
  3. Tested with pandas 1.0.5.
like image 67
timgeb Avatar answered Oct 16 '25 17:10

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!