微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – Pandas将字符串列和NaN(浮点数)转换为整数,保持NaN

参见英文答案 > Convert Pandas column containing NaNs to dtype `int`                                     11个
我在转换包含字符串格式(类型:str)和NaN(类型:float64)的2位数字的列时遇到问题.我想以这种方式获得一个新列:NaN,其中有NaN和整数,其中有两个数字的字符串格式.
举个例子:我想从列YearBirth1获取列Yearbirth2,如下所示:

YearBirth1  #numbers here are formatted as strings: type(YearBirth1[0])=str
        34  # and NaN are floats: type(YearBirth1[2])=float64.
        76
       Nan
        09
       Nan
        91

YearBirth2  #numbers here are formatted as integers: type(YearBirth2[0])=int
        34  #NaN can remain floats as they were. 
        76
       Nan
         9
       Nan
        91

我试过这个:

csv['YearBirth2'] = (csv['YearBirth1']).astype(int)

正如我所料,我得到了这个错误

ValueError: cannot convert float NaN to integer

所以我尝试了这个:

csv['YearBirth2'] = (csv['YearBirth1']!=NaN).astype(int)

并得到这个错误

NameError: name 'NaN' is not defined

最后我试过这个:

csv['YearBirth2'] = (csv['YearBirth1']!='NaN').astype(int)

没有错误,但当我检查列YearBirth2时,这是结果:

YearBirth2:
         1
         1
         1
         1
         1
         1

非常糟糕..我认为这个想法是对的,但是有一个问题让Python能够理解我对NaN的意思..或者我尝试的方法可能是错的..

我也使用了pd.to_numeric()方法,但这种方式我获得了浮点数,而不是整数.

有什么帮助?!
谢谢大家!

P.S:csv是我的DataFrame的名称;
对不起,如果我不太清楚,我正在改进英语!

解决方法:

您可以使用to_numeric,但不可能使用NaN值获取int – 它们始终转换为float:see na type promotions.

df['YearBirth2'] = pd.to_numeric(df.YearBirth1, errors='coerce')
print (df)
  YearBirth1  YearBirth2
0         34        34.0
1         76        76.0
2        Nan         NaN
3         09         9.0
4        Nan         NaN
5         91        91.0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐