首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >收到错误: ValueError:无法将非限定值(NA或inf)转换为整数

收到错误: ValueError:无法将非限定值(NA或inf)转换为整数
EN

Stack Overflow用户
提问于 2021-08-26 09:03:11
回答 1查看 54关注 0票数 0

我应用了以下代码:

代码语言:javascript
运行
复制
# Counting genre_id
def genre_id_count(x):
    if x == 'no_genre_id':
        return 0
    else:
        return x.count('|') + 1

# filling NA in place of null values
train['genre_ids'].cat.add_categories('no_genre_id').fillna('no_genre_id', inplace=True)
test['genre_ids'].cat.add_categories('no_genre_id').fillna('no_genre_id', inplace=True)
train['genre_ids_count'] = train['genre_ids'].apply(genre_id_count).astype(np.int8)
test['genre_ids_count'] = test['genre_ids'].apply(genre_id_count).astype(np.int8)

但是,得到了以下错误:

代码语言:javascript
运行
复制
ValueError                                Traceback (most recent call last)
<ipython-input-17-410362445e25> in <module>
     11 train['genre_ids'].cat.add_categories('no_genre_id').fillna('no_genre_id', inplace=True)
     12 test['genre_ids'].cat.add_categories('no_genre_id').fillna('no_genre_id', inplace=True)
---> 13 train['genre_ids_count'] = train['genre_ids'].apply(genre_id_count).astype(np.int8)
     14 test['genre_ids_count'] = test['genre_ids'].apply(genre_id_count).astype(np.int8)

ValueError: Cannot convert non-finite values (NA or inf) to integer
EN

Stack Overflow用户

发布于 2021-08-26 09:43:52

代码不能工作的原因如下:当您应用train['genre_ids'].cat.add_categories('no_genre_id')时,此方法将返回一个新的pandas序列。您可以将.fillna('no_genre_id', inplace=True)应用于这个新系列。当您设置inplace=True时,这个新的序列会被修改-并且在命令执行后立即从内存中删除,因为它没有存储在变量中。

由于原始系列train['genre_ids']未被修改,因此它仍然包含NA值。整数列不能在pandas中包含NaN值(这仅适用于float列),因此pandas不知道如何将这些值转换为整数,从而导致代码失败。

为了防止这种情况,你必须选择:你可以写成

代码语言:javascript
运行
复制
train['genre_ids'] = train['genre_ids'].cat.add_categories('no_genre_id').fillna('no_genre_id')

或者您可以使用

代码语言:javascript
运行
复制
train['genre_ids'].cat.add_categories('no_genre_id', inplace=True)
train['genre_ids'].fillna('no_genre_id', inplace=True)

在第一个版本中,cat.add_categoriesfillna方法都不修改原始序列,而是创建新序列并返回它们。将fillna方法应用于cat.add_categories的输出-然后使用fillna的输出覆盖原始序列train['genre_ids']

在第二个版本中,两种方法都会修改原始序列,并且不返回任何内容。但是,由于cat.add_categories修改了原始序列并且不返回任何内容,所以我们不能链接这些方法,您必须在train['genre_ids']上直接调用这两个方法。

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68935602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档