列中 select 个数值的平均值
mean of the select number of numerical values from a column
从列年龄我想 select 年龄组在 (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 岁之间
从年龄列中,我想 select 年龄组在 (15 & 45) 之间,然后用年龄组 (15 & 45) 的平均值替换缺失值
为第 Age
列添加括号和 loc
:
m = train.loc[(train['Age'] > 15) & (train['Age'] < 45), 'Age'].mean()
或使用Series.between
:
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())
从列年龄我想 select 年龄组在 (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 岁之间 从年龄列中,我想 select 年龄组在 (15 & 45) 之间,然后用年龄组 (15 & 45) 的平均值替换缺失值
为第 Age
列添加括号和 loc
:
m = train.loc[(train['Age'] > 15) & (train['Age'] < 45), 'Age'].mean()
或使用Series.between
:
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())