脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - pandas 使用均值填充缺失值列的小技巧分享

pandas 使用均值填充缺失值列的小技巧分享

2021-08-01 00:31kate-kk Python

今天小编就为大家分享一篇pandas 使用均值填充缺失值列的小技巧分享,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

pd.DataFrame中通常含有许多特征,有时候需要对每个含有缺失值的列,都用均值进行填充,代码实现可以这样:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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')

以上这篇pandas 使用均值填充缺失值列的小技巧分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Guo_ya_nan/article/details/80878929

延伸 · 阅读

精彩推荐