我正在尝试用空列表 [] 替换数据中的一些 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
and 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,它将尝试将形状对齐回原始系列
EDIT
使用更新后的示例可以实现以下效果:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)