【问题标题】:Change column type from object to float but got TypeError将列类型从对象更改为浮点但得到 TypeError
【发布时间】:2020-11-06 16:25:23
【问题描述】:

我的列类型有问题。
该列是这样的:

# df
col1
0.7368
0.5
NaT
0.2

print(df.dtypes)
col1   object

我想将col1 更改为float 数据类型,但得到了TypeError

df.col1_new = df.col1.astype(float)

TypeError: float() argument must be a string or a number, not 'NaTType'

我需要将NaT 更改为空格吗?我认为NaT应该被视为失踪......

【问题讨论】:

    标签: python pandas data-manipulation


    【解决方案1】:

    试试to_numeric

    pd.to_numeric(df.col1,errors='coerce')
    Out[33]: 
    0    0.7368
    1    0.5000
    2       NaN
    3    0.2000
    Name: col1, dtype: float64
    

    这里的问题是列是str类型

    df.col1.apply(type)
    Out[34]: 
    0    <class 'str'>
    1    <class 'str'>
    2    <class 'str'>
    3    <class 'str'>
    Name: col1, dtype: object
    

    【讨论】:

      【解决方案2】:

      您可以先使用.notnull() 删除NaT

      df.loc[df['b'].notnull(),'b'].astype(float)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 2018-12-09
        • 2014-07-31
        相关资源
        最近更新 更多