代码之家  ›  专栏  ›  技术社区  ›  bolthy

将数据帧中的值从对象转换为整数/浮点数,但它们仍作为对象运行

  •  1
  • bolthy  · 技术社区  · 9 月前

    我的数据帧中有一组值,这些值是写为“100%”、“75%”等的对象 我正在将这些转换为整数(100、75等)

    这是我的功能

    def convert_object_to_int(column):                                           
        column = column.astype(str)                                              
        column = column.str.rstrip('%')                                          
        column = pd.to_numeric(column, errors='coerce')                          
        column = column.fillna(column.median())                                  
        return column.astype(int)
    

    使用以下命令调用函数后:

    a1data.loc[:, 'Total(%)'] = convert_object_to_int(a1data['Total(%)'])
    

    检查时,我的总计(%)列仍显示为对象 a1data.dtypes()

    数字已经发生了变化,我能够在可视化和其他方面使用它们,但是,我无法对数据进行基本的描述性统计,因为它给了我分类描述。

    我是个初学者,所以任何建议都将不胜感激。

    我试着转换为浮点数,因为我读到int64曾经有一些问题。函数中的很多行感觉有点不必要,但直到所有这些行都存在,数字才发生了适当的变化。这些数字现在显示了我想要的结果,但它们仍然可以作为描述性统计和其他功能的对象。

    1 回复  |  直到 9 月前
        1
  •  0
  •   mozway    9 月前

    这是因为您为现有系列分配了 a1data.loc[:, 'Total(%)'] ,它保持了原始的dtype。相反,用新的系列覆盖:

    a1data['Total(%)'] = convert_object_to_int(a1data['Total(%)'])
    
    print(a1data.dtypes)
    # Total(%)    int64
    # dtype: object
    

    另请注意,您不需要重新分配函数中的所有中间体,您可以将其简化为:

    def convert_object_to_int(column):                                           
        column = pd.to_numeric(column.astype(str)
                                     .str.rstrip('%'),
                               errors='coerce')
        return column.fillna(column.median()).astype(int)
    

    或者没有任何变量:

    def convert_object_to_int(column):                                           
        return (pd.to_numeric(column.astype(str)
                                    .str.rstrip('%'),
                              errors='coerce')
                  .pipe(lambda x: x.fillna(x.median()))
                  .astype(int)
               )