pandas -在分类数据中填充NaN [英] Pandas - filling NaNs in Categorical data

查看:68
本文介绍了 pandas -在分类数据中填充NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码填充缺失值(NAN)

I am trying to fill missing values (NAN) using the below code

NAN_SUBSTITUTION_VALUE = 1
g = g.fillna(NAN_SUBSTITUTION_VALUE)

但是出现以下错误

ValueError: fill value must be in categories.

请任何人对此错误有所说明.

Would anybody please throw some light on this error.

推荐答案

您的问题缺少g的要点,尤其是它的dtype为categorical.我认为是这样的:

Your question is missing the important point what g is, especially that it has dtype categorical. I assume it is something like this:

g = pd.Series(["A", "B", "C", np.nan], dtype="category")

您遇到的问题是fillna需要一个已经作为类别存在的值.例如,g.fillna("A")可以工作,但是g.fillna("D")失败.要用新值填充系列,您可以执行以下操作:

The problem you are experiencing is that fillna requires a value that already exists as a category. For instance, g.fillna("A") would work, but g.fillna("D") fails. To fill the series with a new value you can do:

g_without_nan = g.cat.add_categories("D").fillna("D")

这篇关于 pandas -在分类数据中填充NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆