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

Pandas converting column of strings and NaN (floats) to integers, keeping the NaN

我在转换包含字符串格式(类型:str)和 NaN(类型:float64)的 2 位数字的列时遇到问题。我想获得一个以这种方式制作的新列:NaN 那里有 NaN 和整数,那里有许多 2 位数字的字符串格式。 例如:我想从列 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, but is impossible get int with NaN values - they are always converted to 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