【问题标题】:Pandas astype throwing invalid literal for int() with base 10 errorPandas astype 为 int() 抛出无效的文字,以 10 为底错误
【发布时间】:2021-08-19 19:33:13
【问题描述】:

我有一个 pandas 数据框 df,其列名和数据类型在另一个文件中指定(读取为 data_dict)。因此,为了正确获取数据,我使用以下代码:

col_list = data_dict['name'].tolist()
dtype_list = data_dict['type'].tolist()
dtype_dict = {col_list[i]: dtype_list[i] for i in range(len(col_list))}
df.columns = col_list
df = df.fillna(0)
df = df.astype(dtype_dict)

但它抛出了这个错误:

以 10 为基数的 int() 的无效文字:'2.230'

我在网上搜索的大多数答案都推荐使用pd.to_numeric()df[col1].astype(float).astype(int) 之类的东西。这里的问题是df 包含 50+ 列,其中大约 30 列应转换为整数类型。因此,我不想一次将数据类型转换为一列。

那么我怎样才能轻松修复这个错误呢?

【问题讨论】:

  • 您的问题到底是什么?如何为多列设置浮点类型?

标签: python pandas


【解决方案1】:

通过布尔掩码尝试:

mask=df.apply(lambda x:x.str.isalpha(),1).fillna(False)

最后:

df[~mask]=df[~mask].astype(float).astype(int)

或者

cols=df[~mask].dropna(axis=1).columns
df[cols]=df[cols].astype(float).astype(int)

【讨论】:

    【解决方案2】:

    df[col_list] = pd.to_numeric(df[col_list])

    【讨论】:

      【解决方案3】:

      您可以像这样设置整个数据框的数据类型:

      import pandas as pd
      df = pd.DataFrame({'A': map(str, np.random.rand(10)), 'B': np.random.rand(10)})
      df.apply(pd.to_numeric)
      
                A         B
      0  0.493771  0.389934
      1  0.991265  0.387819
      2  0.398947  0.128031
      3  0.869156  0.007609
      4  0.129748  0.532235
      5  0.993632  0.882933
      6  0.244311  0.213737
      7  0.773192  0.229257
      8  0.392530  0.339418
      9  0.732609  0.685258
      

      对于一些这样的列:

      df[['A', 'B']] = df[['A', 'B']].apply(pd.to_numeric)
      

      如果您想在不知道哪一列有数字的情况下将整个数据帧的类型转换为浮点数,可以使用以下方法:

      import pandas as pd
      df = pd.DataFrame({'A': map(str, np.random.rand(10)), 'B': np.random.rand(10), 'C': [x for x in 'ABCDEFGHIJ']})
      
      def to_num(df):
          for col in df:
              try:
                  df[col] = pd.to_numeric(df[col])
              except:
                  continue
          return df
      
      df.pipe(to_num)
      
                A         B  C
      0  0.762027  0.095877  A
      1  0.647066  0.931435  B
      2  0.016939  0.806675  C
      3  0.260255  0.346676  D
      4  0.561694  0.551960  E
      5  0.561363  0.675580  F
      6  0.312432  0.498806  G
      7  0.353007  0.203697  H
      8  0.418549  0.128924  I
      9  0.728632  0.600307  J
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-28
        • 2012-05-14
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多