【问题标题】:Cannot convert pandas column from string to int无法将 pandas 列从字符串转换为 int
【发布时间】:2017-02-04 03:53:09
【问题描述】:

数据框中的下面的列需要转换为int:

dsAttendEnroll.District.head()

0    DISTRICT 01
1    DISTRICT 02
2    DISTRICT 03
3    DISTRICT 04
4    DISTRICT 05
Name: District, dtype: object

使用 astype 会出现以下错误,怎么办?

dsAttendEnroll.District = dsAttendEnroll.District.map(lambda x: x[-2:]).astype(int)

ValueError: 以 10 为底的 long() 的无效文字:'LS'

【问题讨论】:

  • 这意味着你的数据有一些以LS...
  • 我认为你首先需要决定你想用LS 数据做什么。您要丢弃它还是将其拆分为单独的列(如下所示)? LS 有效还是无效?
  • 感谢过滤掉不正确的数据解决了这个问题。

标签: string python-2.7 pandas int


【解决方案1】:

您可以使用splitstr[1]to_numeric 选择第二个列表,其中参数errors='coerce' - 它不是将数值转换为NaN

print (df)
      District
0  DISTRICT 01
1  DISTRICT 02
2  DISTRICT 03
3  DISTRICT 04
4  DISTRICT 05
5  DISTRICT LS

print (df.District.str.split().str[1])
0    01
1    02
2    03
3    04
4    05
5    LS
Name: District, dtype: object

print (pd.to_numeric(df.District.str.split().str[1], errors='coerce'))
0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
5    NaN
Name: District, dtype: float64

使用切片 2 最后一个字符的另一种解决方案:

print (df.District.str[-2:])
0    01
1    02
2    03
3    04
4    05
5    LS
Name: District, dtype: object

print (pd.to_numeric(df.District.str[-2:], errors='coerce'))
0    1.0
1    2.0
2    3.0
3    4.0
4    5.0
5    NaN
Name: District, dtype: float64

【讨论】:

  • 我添加了另一个解决方案,请检查一下。
【解决方案2】:

你可以试试:

dsAttendEnroll.District=pd.to_numeric(dsAttendEnroll.District)
dsAttendEnroll.District=dsAttendEnroll.District.astype(int)

查看文档here

【讨论】:

    猜你喜欢
    • 2019-04-08
    • 2018-05-10
    • 2020-04-08
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    相关资源
    最近更新 更多