pandas fillna引发ValueError:填充值必须在类别中 [英] Pandas fillna throws ValueError: fill value must be in categories

查看:260
本文介绍了 pandas fillna引发ValueError:填充值必须在类别中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明:两个功能均属于类别dtypes.我在相同的不同内核中使用了此代码 dateset工作正常,唯一的区别是功能在flote64中.后来我已经将这些功能dtypes转换为Categorical 因为数据集中的所有要素都代表类别.

Discription: both features are in categorical dtypes. and i used this code in a different kernal of same dateset was working fine, the only difference is the features are in flote64. later i have converted these feature dtypes into Categorical because all the features in the dataset represents categories.

下面是代码:

AM_train['product_category_2'].fillna('Unknown', inplace =True)
AM_train['city_development_index'].fillna('Missing', inplace =True)

推荐答案

使用

Use Series.cat.add_categories for add categories first:

AM_train['product_category_2'] = AM_train['product_category_2'].cat.add_categories('Unknown')
AM_train['product_category_2'].fillna('Unknown', inplace =True) 

AM_train['city_development_index'] = AM_train['city_development_index'].cat.add_categories('Missing')
AM_train['city_development_index'].fillna('Missing', inplace =True)

示例:

AM_train = pd.DataFrame({'product_category_2': pd.Categorical(['a','b',np.nan])})
AM_train['product_category_2'] = AM_train['product_category_2'].cat.add_categories('Unknown')
AM_train['product_category_2'].fillna('Unknown', inplace =True) 

print (AM_train)
  product_category_2
0                  a
1                  b
2            Unknown

这篇关于 pandas fillna引发ValueError:填充值必须在类别中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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