python - 用 Pandas 数据框中的空列表替换 NaN

标签 python pandas dataframe

我正在尝试用一个空列表 [] 替换我数据中的一些 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

最佳答案

这可以使用 isnullloc 来屏蔽系列:

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/

相关文章:

python - 从满足条件的最后一行开始的 Pandas 累积总和

python - R 到 Python : Using Shift with ifelse

python - 如何通过复制上一行来动态创建新行

r - 根据其他行是否唯一来选择行的值

python - 汇总矩阵中的每个列值

python - 比较两列值并从第一列获取不同的值

Python Pandas 在 For 循环中替换列中的字符串

python - 如何将 python 3.5.1 与 MySQL 数据库一起使用

python - 用指向 URL 的链接替换文本中的 URL

python - pandas.plot(...) 意外反转 x 轴