我正在尝试用一个空列表 [] 替换我数据中的一些 NaN 值。但是,该列表表示为 str 并且不允许我正确应用 len() 函数。有没有办法用 pandas 中的实际空列表替换 NaN 值?
In [28]: d = pd.DataFrame({'x' : [[1,2,3], [1,2], np.NaN, np.NaN], 'y' : [1,2,3,4]})
In [29]: d
Out[29]:
x y
0 [1, 2, 3] 1
1 [1, 2] 2
2 NaN 3
3 NaN 4
In [32]: d.x.replace(np.NaN, '[]', inplace=True)
In [33]: d
Out[33]:
x y
0 [1, 2, 3] 1
1 [1, 2] 2
2 [] 3
3 [] 4
In [34]: d.x.apply(len)
Out[34]:
0 3
1 2
2 2
3 2
Name: x, dtype: int64
最佳答案
这可以使用 isnull
和 loc
来屏蔽系列:
In [90]:
d.loc[d.isnull()] = d.loc[d.isnull()].apply(lambda x: [])
d
Out[90]:
0 [1, 2, 3]
1 [1, 2]
2 []
3 []
dtype: object
In [91]:
d.apply(len)
Out[91]:
0 3
1 2
2 0
3 0
dtype: int64
您必须使用 apply
来执行此操作,以免列表对象被解释为数组以分配回 df,df 将尝试将形状对齐回原始系列
编辑
使用更新后的示例,以下工作:
In [100]:
d.loc[d['x'].isnull(),['x']] = d.loc[d['x'].isnull(),'x'].apply(lambda x: [])
d
Out[100]:
x y
0 [1, 2, 3] 1
1 [1, 2] 2
2 [] 3
3 [] 4
In [102]:
d['x'].apply(len)
Out[102]:
0 3
1 2
2 0
3 0
Name: x, dtype: int64
关于python - 用 Pandas 数据框中的空列表替换 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567218/