【问题标题】:how to find out in a pandas DF column which values can not be converted to 'int' type with astype function如何在 pandas DF 列中找出哪些值不能使用 astype 函数转换为“int”类型
【发布时间】:2021-07-13 16:38:05
【问题描述】:

我正在使用数据框,我必须将一列转换为 int 类型

我使用以下符号:

result_df['ftmSectionId'] = result_df['ftmSectionId'].astype('int') 

DF 有几百万行,所以显然有些值无法转换为 int(可能包括逗号或句点...)我收到错误:

ValueError: invalid literal for int() with base 10: 'not'

现在根据这个问题: How do I fix invalid literal for int() with base 10 error in pandas

我可以使用:

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

哪个有效。

但是以这种方式,我不知道为什么我首先会出错。 由于我正在使用的数据库的性质,我希望该特定列只有整数。 如何使用简单的方法 .astype('int') 查询列以找出哪些值不能转换为 'int'?

谢谢

其他可能但不重复的答案: Unable to convert pandas dataframe column to int variable type using .astype(int) method 这个问题解决了同样的问题,只是他们知道问题是该列包含 NaN 并且他们删除了它们。我不知道这里有什么问题,我的目标不仅是转换为 'int' 而是抓住麻烦值

【问题讨论】:

    标签: pandas types


    【解决方案1】:

    您仍然可以使用errors="coerce",然后获取原始系列中NaN 的值:

    s = pd.Series(["apple", "1.0", "2", -3, "pear", "12,84"])
    
    nans = pd.to_numeric(s, errors="coerce").isna()
    

    然后布尔索引给出:

    >>> s[nans]
    
    0    apple
    4     pear
    5    12,84
    dtype: object
    

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 2021-11-03
      • 2021-06-03
      • 2021-01-10
      • 2011-08-20
      • 2022-11-29
      • 2017-07-16
      • 1970-01-01
      相关资源
      最近更新 更多