6

给定 a pd.Series,我想用列表替换空值。也就是说,给定:

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

我想要一个可以返回的函数

0        0
1        1
2    [nan]

但是,如果我尝试为此使用自然函数,即fillna

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

但我得到了错误

TypeError:“value”参数必须是标量或字典,但您传递了“list”

关于实现这一目标的简单方法的任何建议?

4

4 回答 4

9

使用apply, 因为fillna只使用标量:

print (ser.apply(lambda x: [np.nan] if pd.isnull(x) else x))
0        0
1        1
2    [nan]
dtype: object
于 2017-11-13T15:06:30.633 回答
3

您可以更改为对象

ser=ser.astype('object')

然后分配列表np.nan

ser.loc[ser.isnull()]=[[np.nan]]
于 2017-11-13T15:23:10.497 回答
1

我最终使用

ser.loc[ser.isnull()] = ser.loc[ser.isnull()].apply(lambda x: [np.nan]) 

因为 pd.isnull(x) 会给我模棱两可的真值错误(我的系列中也有其他列表)。这是 YOBEN_S' 和 jezrael 的答案的组合。

于 2020-07-15T08:12:20.850 回答
0

fillna可以取一个 Series,一个列表可以转换为一个 Series。把你的清单包装起来pd.Series()对我有用:

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

result
0    0.0
1    1.0
2    NaN
dtype: float64
于 2018-06-04T19:54:33.870 回答