pandas 用均值填充缺失值列的技巧

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’)

你可能感兴趣的:(Dataframe)