[英]Convert pandas series to int with NaN values
I have a series (month_addded) in my DataFrame like this:我的 DataFrame 中有一个系列 (month_addded),如下所示:
9.0
12.0
12.0
nan
1.0
I want all the floats to be ints, and the NaN's to stay as they are.我希望所有的浮点数都是整数,而 NaN 则保持原样。 I did this:
我这样做了:
for i in df['month_added']:
if i > 0:
i=int(i)
But it did nothing.但它什么也没做。
NaN
is float typed, so Pandas would always downcast your column to float as long as you have NaN
. NaN
是 float 类型的,所以只要你有NaN
,Pandas 就会总是将你的列向下转换为 float 。 You can use Nullable Integer , available from Pandas 0.24.0:您可以使用Nullable Integer ,可从 Pandas 0.24.0 获得:
df['month_added'] = df['month_added'].astype('Int64')
If that's not possible, you can force Object
type (not recommended):如果那不可能,您可以强制
Object
(不推荐):
df['month_added'] = pd.Series([int(x) if x > 0 else x for x in df.month_added], dtype='O')
Or since your data is positive and NaN
, you can mask NaN
with 0
:或者由于您的数据是正数和
NaN
,您可以用0
屏蔽NaN
:
df['month_added'] = df['month_added'].fillna(0).astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.