pd.dataframe中通常含有许多特征,有时候需要对每个含有缺失值的列,都用均值进行填充,代码实现可以这样:
for column in list(df.columns[df.isnull().sum() > 0]):
mean_val = df[column].mean()
df[column].fillna(mean_val, inplace=true)
# -------代码分解-------
# 判断哪些列有缺失值,得到series对象
df.isnull().sum() > 0
# output
contributors true
coordinates true
created_at false
display_text_range false
entities false
extended_entities true
favorite_count false
favorited false
full_text false
geo true
id false
id_str false
...
# 根据上一步结果,筛选需要填充的列
df.columns[df.isnull().sum() > 0]
# output
index(['contributors', 'coordinates', 'extended_entities', 'geo',
'in_reply_to_screen_name', 'in_reply_to_status_id',
'in_reply_to_status_id_str', 'in_reply_to_user_id',
'in_reply_to_user_id_str', 'place', 'possibly_sensitive',
'possibly_sensitive_appealable', 'quoted_status', 'quoted_status_id',
'quoted_status_id_str', 'retweeted_status'],
dtype='object')