【问题标题】:Invalid literal for int() with base 10 'Washington'基数为 10 'Washington' 的 int() 文字无效
【发布时间】:2021-06-25 01:04:12
【问题描述】:

我正在研究一个有 35 列和 3047 行的基础。其中一列是“州”,它由美国的 50 个州组成,我想将这些州转换为数值,例如华盛顿是 1,西弗吉尼亚是 2,等等。

df.loc[df['State']=='Washington','State']=1
df.loc[df['State']=='West Virginia','State']=2
.
.
df.loc[df['State']=='Arizona','State']=50
df['State']=df['State'].astype(str).astype(int)

我收到此错误:ValueError: int() 的无效文字,基数为 10:'Washington'。 谁能帮我?我能做些什么来解决这个问题?你知道在 int 中转换 dtype 对象的其他方法吗? 提前致谢

【问题讨论】:

标签: python pandas database error-handling integer


【解决方案1】:

假设你有这样的数据框:

           State
0     Washington
1  West Virginia
2        Arizona
3     Washington

然后你可以使用pd.Categorical()将其转换为代码:

df["State"] = pd.Categorical(df["State"]).codes + 1
print(df)

打印:

   State
0      2
1      3
2      1
3      2

【讨论】:

  • 行得通,列状态被转换但与其他列和行不匹配,似乎数字是随机划分的。
猜你喜欢
  • 2013-05-31
  • 2018-03-13
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-06
相关资源
最近更新 更多