合并后为空值

时间:2020-07-17 08:58:57

标签: python pandas dataframe data-science

在使用 pd.cut()将连续变量转换为分类变量的同时,空值出现在“年龄”列中,该列是从“ age_in_years”格式转换的,没有任何空值。解决方案是什么?

df['age_in_years']=df['age_in_days']/365
df.drop('age_in_days',inplace=True,axis=1)
bins=[0,35,60,100]
group=['young','middle_aged','senior']
df['age']=pd.cut(df['age_in_years'],bins,labels=group,right=True).astype('object')

现在,当我运行df.isnull().sum()时,age列将显示空值 image o/p of df.isnull().sum()

数据集:https://drive.google.com/file/d/11_qSL5tI1epiRcOzueYaMT-1GUiwAQvs/view?usp=sharing

2 个答案:

答案 0 :(得分:0)

您可以尝试:

bins=[-np.inf,0,35,60,100,np.inf]
df['age']=pd.cut(df['age_in_years'],bins,labels=group,right=True).astype('object')

这将诊断问题,并且还包括0 (-inf, 0.0]以下和100 [100.0, inf)以上的值

答案 1 :(得分:0)

发生错误是因为您的五行中的age_in_years大于100,并且由于您确定最后一个bin结束于100,所以在构造age时,这五行将获得空值。 / p>

您可以使用float('inf')作为最后一个bin的上限来调整代码:

bins = [0, 35, 60, float('inf')]
group = ['young', 'middle_aged', 'senior']
df['age'] = pd.cut(df['age_in_years'], bins, labels=group, right=False).astype('object')
相关问题