如何将意外数据类型设置为na?

时间:2018-03-13 12:27:36

标签: python pandas

我有一个这样的数据框:

a = pd.DataFrame({'foo':[1,2,3,'str']})

    foo
0   1
1   2
2   3
3   str

我想将数据类型设置为int64:

a['foo'].astype('int32')

但是我收到了一条错误消息:

ValueError: invalid literal for int() with base 10: 'str'

如何将意外数据类型设置为NA。在我的情况下,我想返回如下数据框:

    foo
0   1
1   2
2   3
3   NA

2 个答案:

答案 0 :(得分:4)

最好将所有值转换为float s,因为NaN float位于to_numeric之后,参数errors='coerce'

df = pd.to_numeric(df['foo'], errors='coerce')
print (df)
0    1.0
1    2.0
2    3.0
3    NaN
Name: foo, dtype: float64

但是如果真的需要带浮点数的整数,可能就是这个黑客:

df = df['foo'].where(df['foo'].apply(lambda x: isinstance(x, int)))
print (df)
0      1
1      2
2      3
3    NaN
Name: foo, dtype: object
print (df.apply(type))
0      <class 'int'>
1      <class 'int'>
2      <class 'int'>
3    <class 'float'>
Name: foo, dtype: object

答案 1 :(得分:0)

或使用isalpha

a.foo.mask(a.foo.str.isalpha().notnull())
Out[331]: 
0      1
1      2
2      3
3    NaN
Name: foo, dtype: object