【问题标题】:How to convert datatype:object to float64 in python?如何在 python 中将 datatype:object 转换为 float64?
【发布时间】:2015-04-01 08:43:27
【问题描述】:

我在兜圈子,尝试了很多不同的方法,所以我猜我的核心理解是错误的。如果能帮助我理解我的编码/解码问题,我将不胜感激。

我从 SQL 导入数据框,似乎某些数据类型:float64 被转换为对象。因此,我无法进行任何计算。我无法将 Object 转换回 float64。

df.head()

Date        WD  Manpower 2nd     CTR    2ndU    T1    T2      T3      T4 

2013/4/6    6   NaN     2,645   5.27%   0.29    407     533     454     368
2013/4/7    7   NaN     2,118   5.89%   0.31    257     659     583     369
2013/4/13   6   NaN     2,470   5.38%   0.29    354     531     473   383
2013/4/14   7   NaN     2,033   6.77%   0.37    396     748     681     458
2013/4/20   6   NaN     2,690   5.38%   0.29    361     528     541     381

df.dtypes

WD             float64
Manpower       float64
2nd             object
CTR             object
2ndU           float64
T1              object
T2              object
T3              object
T4              object
T5              object

dtype: object

SQL 表:

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您只需调用convert_objects即可转换大部分列:

    In [36]:
    
    df = df.convert_objects(convert_numeric=True)
    df.dtypes
    Out[36]:
    Date         object
    WD            int64
    Manpower    float64
    2nd          object
    CTR          object
    2ndU        float64
    T1            int64
    T2          int64
    T3           int64
    T4        float64
    dtype: object
    

    对于列'2nd'和'CTR',我们可以调用向量化的str方法来替换千位分隔符并删除'%'符号,然后astype进行转换:

    In [39]:
    
    df['2nd'] = df['2nd'].str.replace(',','').astype(int)
    df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
    df.dtypes
    Out[39]:
    Date         object
    WD            int64
    Manpower    float64
    2nd           int32
    CTR         float64
    2ndU        float64
    T1            int64
    T2            int64
    T3            int64
    T4           object
    dtype: object
    In [40]:
    
    df.head()
    Out[40]:
            Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
    0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
    1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
    2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
    3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
    4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381
    

    或者您可以在不调用astype 的情况下执行上述字符串处理操作,然后调用convert_objects 一次性转换所有内容。

    更新

    由于版本 0.17.0 convert_objects 已弃用并且没有顶级函数可以执行此操作,因此您需要这样做:

    df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

    请参阅docs 和此相关问题:pandas: to_numeric for multiple columns

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      df['2nd'] = pd.to_numeric(df['2nd'].str.replace(',', ''))
      df['CTR'] = pd.to_numeric(df['CTR'].str.replace('%', ''))
      

      【讨论】:

        【解决方案3】:

        或者你可以使用正则表达式来处理多个项目作为这个问题的一般情况,

        df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
        df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))
        

        【讨论】:

          【解决方案4】:

          convert_objects 已弃用。

          对于pandas >= 0.17.0,使用pd.to_numeric

          df["2nd"] = pd.to_numeric(df["2nd"])
          

          【讨论】:

            【解决方案5】:

            我在从具有多个内部标题行的 Excel 工作表创建的 DataFrame (df) 中遇到了这个问题。

            df 中清除内部标题行后,列的值为“非空对象”类型(DataFrame.info())。

            这段代码一次性将多列的所有数值转换为int64和float64:

            for i in range(0, len(df.columns)):
                df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
                # errors='ignore' lets strings remain as 'non-null objects'
            

            【讨论】:

              【解决方案6】:
              X = np.array(X, dtype=float)
              

              您可以在 python 3.7.6 中使用它来转换为浮点数组

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-12-22
                • 2011-12-22
                • 1970-01-01
                • 2021-04-30
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多