在 Pandas 中重命名“None”值

10

这可能非常简单,但我就是找不到答案。我使用GeoPandas从shape文件中导入数据,将其转换为pandas DataFrame。我有一个包含三个字母代码和缺失数据的None值的对象字段。如何在pandas中将None更改为“vcv”之类的东西?我尝试了以下方法:

sala.replace(None,"vcv")

遇到了这个错误

   2400                                     "strings or regular expressions, you "
   2401                                     "passed a"
-> 2402                                     " {0!r}".format(type(regex).__name__))
   2403                 return self.replace(regex, value, inplace=inplace, limit=limit,
   2404                                     regex=True)

TypeError: 'regex' must be a string or a compiled regular expression or a list or dict of strings or regular expressions, you passed a 'bool'

尝试了这个

if sala['N10'] is None:
    sala['N10'] = 'Nul'

不会改变任何东西。


你是指字符串“None”还是空字符串? - EdChum
您可以使用sala['N10'].isnull()来测试空值,因此您可以执行sala.loc[sala['N10'].isnull(), 'N10'] = 'vcv' - EdChum
3
我觉得你的回答sala.fillna(value='vcv')是可以的。为什么删除了? - unutbu
是的,它是“None”。Ajean:我只需要更改列,而不是您建议的表中的所有内容。我有很多数字,所以vcv行不通。我正在使用文本字段进行合并,但它无法与“None”一起使用。 - user1246428
sala.loc[sala['N10'] == 'None', 'N10'] = 'vcv' 这样写可以吗? - EdChum
1个回答

16

最简单的方法就是:

sala['N10'].replace('None', 'vcv', inplace=True)

应该可以正常工作。

如果它们是真正的NaN值,那么调用fillna就会起作用。

例如:

sala['N10'].fillna(value='vcv', inplace = True)

另外,我在我的评论中提出的建议:

sala.loc[sala['N10'].isnull(), 'N10'] = 'vcv'

2
好的,小的沟通失误,实际上它是没有值,但在打印时显示为“None”。但它不是文本“None”。您的解决方案sala.loc[sala['N10'].isnull(), 'N10'] = 'vcv'非常好。谢谢,马修。 - user1246428

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接