[英]How to impute entire missing values in pandas dataframe with mode/mean?
I know codes forfilling seperately by taking each column as below我知道通过将每一列分别填充的代码如下
data['Native Country'].fillna(data['Native Country'].mode(), inplace=True)
But i am working on a dataset with 50 rows and there are 20 categorical values which need to be imputed.但我正在处理一个有 50 行的数据集,并且有 20 个分类值需要估算。 Is there a single line code for imputing the entire data set??是否有用于估算整个数据集的单行代码?
Use DataFrame.fillna
with DataFrame.mode
and select first row because if same maximum occurancies is returned all values:将DataFrame.fillna
与DataFrame.mode
和 select 第一行一起使用,因为如果返回相同的最大出现次数,则所有值:
data = pd.DataFrame({
'A':list('abcdef'),
'col1':[4,5,4,5,5,4],
'col2':[np.nan,8,3,3,2,3],
'col3':[3,3,5,5,np.nan,np.nan],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})
cols = ['col1','col2','col3']
print (data[cols].mode())
col1 col2 col3
0 4 3.0 3.0
1 5 NaN 5.0
data[cols] = data[cols].fillna(data[cols].mode().iloc[0])
print (data)
A col1 col2 col3 E F
0 a 4 3.0 3.0 5 a
1 b 5 8.0 3.0 3 a
2 c 4 3.0 5.0 6 a
3 d 5 3.0 5.0 9 b
4 e 5 2.0 3.0 2 b
5 f 4 3.0 3.0 4 b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.