舍入。仅填充值。不是python中的整个列
我试图创建一个函数,根据均值或中位数的选择来插补值 我已经设法做到了,我的问题是我只想舍入我估算的值。但我的方法是对列中的每个值进行四舍五入,而不仅仅是根据需要对填充的值进行四舍五入舍入。仅填充值。不是python中的整个列,python,rounding,fillna,Python,Rounding,Fillna,我试图创建一个函数,根据均值或中位数的选择来插补值 我已经设法做到了,我的问题是我只想舍入我估算的值。但我的方法是对列中的每个值进行四舍五入,而不仅仅是根据需要对填充的值进行四舍五入 def conditional_impute(input_df, choice='median'): new_df = input_df.copy() if choice == 'median': new_df['Age'] = round(new_df.groupby([
def conditional_impute(input_df, choice='median'):
new_df = input_df.copy()
if choice == 'median':
new_df['Age'] = round(new_df.groupby(['Sex', 'Pclass'])['Age'].transform(func = lambda x: x.fillna(x.median())),1)
elif choice == 'mean':
new_df['Age'] = round(new_df.groupby(['Sex', 'Pclass'])['Age'].transform(func = lambda x: x.fillna(x.mean())),1)
else:
raise ValueError('Please choose either median or mean as your impute choice.')
return new_df
那么,如何仅对插补值进行四舍五入呢?您可以对整个列应用四舍五入函数。您是否尝试过这样的方法,并仅将其应用于中位数(或平均值)
非常感谢。我试过了,但我的回合打错了括号!
if choice == 'median':
new_df['Age'] = new_df.groupby(['Sex', 'Pclass'])['Age'].transform(func = lambda x: x.fillna(round(x.median(),1)))