13

这是每当我尝试将数据帧转换为 int 时出现的错误。

("invalid literal for int() with base 10: '260,327,021'", '发生在索引 Population1'

df 中的所有内容都是一个数字。我认为错误是由于末尾的额外引号引起的,但我该如何解决?

4

4 回答 4

17

我运行这个

int('260,327,021')

得到这个

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-448-a3ba7c4bd4fe> in <module>()
----> 1 int('260,327,021')

ValueError: invalid literal for int() with base 10: '260,327,021'

我向您保证,并非数据框中的所有内容都是数字。它可能看起来像一个数字,但它是一个带有逗号的字符串。

你会想要替换你的逗号,然后转向int

pd.Series(['260,327,021']).str.replace(',', '').astype(int)

0    260327021
dtype: int64
于 2017-05-08T23:17:32.003 回答
9

当字符串是浮点数时,其他人可能会遇到以下问题:

    >>> int("34.54545")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '34.54545'

解决方法是先转换为浮点数,然后再转换为 int:

>>> int(float("34.54545"))
34

或特定于熊猫:

df.astype(float).astype(int)
于 2018-03-03T20:37:09.247 回答
4

我使用pandas.to_numeric解决了错误

在你的情况下,

data.Population1 = pd.to_numeric(data.Population1, errors="coerce")

“数据”是父对象。

之后,您也可以将 float 转换为 int

data.Population1.astype(int)
于 2020-01-17T09:07:18.883 回答
0

对我来说,情况有点不同。

我这样加载了我的数据框:

my_converter = {'filename': str, 'revision_id': int}

df = pd.read_csv("my.csv", header=0, sep="\t", converters=my_converter)

因为head -n 3 my.csv看起来像这样:

"filename"     "revision_id"
"some_filename.pdf"     "224"
"another_filename.pdf"     "128"

然而,在数千行之后,有一个这样的条目:

 "very_\"special\"_filename.pdf"     "46"

这意味着我必须将转义字符指定给read_csv(). 否则,它会尝试强制转换为special字段并生成错误。intrevision_id

所以正确的做法是:

df = pd.read_csv("my.csv", header=0, sep="\t",  escapechar='\\', converters=my_converter)
于 2021-01-19T16:04:31.897 回答