将列类型从对象更改为浮动但出现TypeError

时间:2020-11-06 16:25:23

标签: python pandas data-manipulation

列类型有问题。
该列类似于:

# 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应该被认为是丢失的...

2 个答案:

答案 0 :(得分:3)

尝试使用{ // other form key/value, cnicExpiry: "undefined-undefined-undefined" }

to_numeric

这里的问题是列是str类型

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

答案 1 :(得分:1)

您可以先使用NaT放下.notnull()

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