从一列中选择的数值的平均数

2024-09-29 01:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

从“年龄”列中,我要选择介于(15&45)之间的年龄组,然后用年龄组(15&45)的平均值替换缺少的值

[IN]: train['Age'].isnull().value_counts()
[OUT]:
False    714
True     177
Name: Age, dtype: int64

如何编写此代码?你知道吗

大多数解决方案都涉及基于布尔的输出

train['Age'].fillna((train['Age'] > 15 & train['Age'] < 45).mean())

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

train['Age'].fillna((train['Age'] > 15 & train['Age'] < 45).mean())

年龄组分布在1到80岁之间 从“年龄”列中,我要选择介于(15&45)之间的年龄组,然后用年龄组(15&45)的平均值替换缺少的值


Tags: nameinfalsetrueagevaluetrainout
2条回答

Age列添加括号和loc

m = train.loc[(train['Age'] > 15) & (train['Age'] < 45), 'Age'].mean()

或者使用^{}

m = train.loc[train['Age'].between(15, 45, inclusive=False), 'Age'].mean()

最后替换缺少的值:

train['Age'] = train['Age'].fillna(m)
train['Age'].fillna(train.Age[(train['Age'] > 15) & (train['Age'] < 45) ].mean())

相关问题 更多 >