如何在pandas中使用base 10错误修复int()的无效文字

问题描述 投票:1回答:2

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

(“具有基数10的int()的无效文字:'260,327,021'”,'发生在索引Population1'

df中的所有内容都是数字。我假设错误是由于最后的额外报价,但我该如何解决?

python-2.7 pandas int jupyter-notebook valueerror
2个回答
2
投票

我跑了这个

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

0
投票

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

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

解决方法是首先转换为float,然后转换为int:

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

或者特定的熊猫:

df.astype(float).astype(int)
© www.soinside.com 2019 - 2024. All rights reserved.