【问题标题】:why astype is not chance type of values?为什么 astype 不是机会类型的值?
【发布时间】:2020-10-30 12:01:33
【问题描述】:
df = pd.DataFrame({"A" : ["1", "7.0", "xyz"]})
type(df.A[0])

结果是“str”。

df.A = df.A.astype(int, errors = "ignore")
type(df.A[0])

结果也是“str”。我想将“1”和“7.0”转换为 1 和 7。

我哪里做错了?

【问题讨论】:

    标签: pandas type-conversion


    【解决方案1】:

    为什么 astype 不是机会类型的值?

    因为errors = "ignore" 的工作方式与您想象的不同。

    如果失败,它会返回相同的值,所以没有任何变化。

    如果想要数字值,如果失败则NaN

    df['A'] = pd.to_numeric(df['A'], errors='coerce').astype('Int64')
    print (df)
          A
    0     1
    1     7
    2  <NA>
    

    对于混合值 - 带字符串的数字:

    def num(x):
        try:
            return(int(float(x)))
        except:
            return x
    
    df['A'] = df['A'].apply(num)
    print (df)
    
    0    1
    1    7
    2  xyz
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      相关资源
      最近更新 更多