经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python?pandas处理缺失值方法详解(dropna、drop、fillna)
来源:jb51  时间:2022/8/16 9:54:40  对本文有异议

面对缺失值三种处理方法:

  • option 1: 去掉含有缺失值的样本(行)
  • option 2:将含有缺失值的列(特征向量)去掉
  • option 3:将缺失值用某些值填充(0,平均值,中值等)

对于dropna和fillna,dataframe和series都有,在这主要讲datafame的

对于option1:

使用DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

参数说明:

  • axis:
    • axis=0: 删除包含缺失值的行
    • axis=1: 删除包含缺失值的列
  • how: 与axis配合使用
    • how=‘any’ :只要有缺失值出现,就删除该行货列
    • how=‘all’: 所有的值都缺失,才删除行或列
  • thresh: axis中至少有thresh个非缺失值,否则删除
  • 比如 axis=0,thresh=10:标识如果该行中非缺失值的数量小于10,将删除改行
  • subset: list
  • 在哪些列中查看是否有缺失值
  • inplace: 是否在原数据上操作。如果为真,返回None否则返回新的copy,去掉了缺失值

建议在使用时将全部的缺省参数都写上,便于快速理解

examples:

  1. df = pd.DataFrame(
  2. {"name": ['Alfred', 'Batman', 'Catwoman'],
  3. "toy": [np.nan, 'Batmobile', 'Bullwhip'],
  4. "born": [pd.NaT, pd.Timestamp("1940-04-25")
  5. pd.NaT]})
  6. >>> df
  7. name toy born
  8. 0 Alfred NaN NaT
  9. 1 Batman Batmobile 1940-04-25
  10. 2 Catwoman Bullwhip NaT
  11. # Drop the rows where at least one element is missing.
  12. >>> df.dropna()
  13. name toy born
  14. 1 Batman Batmobile 1940-04-25
  15. # Drop the columns where at least one element is missing.
  16. >>> df.dropna(axis='columns')
  17. name
  18. 0 Alfred
  19. 1 Batman
  20. 2 Catwoman
  21. # Drop the rows where all elements are missing.
  22. >>> df.dropna(how='all')
  23. name toy born
  24. 0 Alfred NaN NaT
  25. 1 Batman Batmobile 1940-04-25
  26. 2 Catwoman Bullwhip NaT
  27. # Keep only the rows with at least 2 non-NA values.
  28. >>> df.dropna(thresh=2)
  29. name toy born
  30. 1 Batman Batmobile 1940-04-25
  31. 2 Catwoman Bullwhip NaT
  32. # Define in which columns to look for missing values.
  33. >>> df.dropna(subset=['name', 'born'])
  34. name toy born
  35. 1 Batman Batmobile 1940-04-25
  36. # Keep the DataFrame with valid entries in the same variable.
  37. >>> df.dropna(inplace=True)
  38. >>> df
  39. name toy born
  40. 1 Batman Batmobile 1940-04-25

对于option 2:

可以使用dropna 或者drop函数
DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

  • labels: 要删除行或列的列表
  • axis: 0 行 ;1 列
  1. df = pd.DataFrame(np.arange(12).reshape(3,4),
  2. columns=['A', 'B', 'C', 'D'])
  3. >>>df
  4. A B C D
  5. 0 0 1 2 3
  6. 1 4 5 6 7
  7. 2 8 9 10 11
  8.  
  9. # 删除列
  10. >>> df.drop(['B', 'C'], axis=1)
  11. A D
  12. 0 0 3
  13. 1 4 7
  14. 2 8 11
  15. >>> df.drop(columns=['B', 'C'])
  16. A D
  17. 0 0 3
  18. 1 4 7
  19. 2 8 11
  20. # 删除行(索引)
  21. >>> df.drop([0, 1])
  22. A B C D
  23. 2 8 9 10 11

对于option3

使用DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)

  • value: scalar, dict, Series, or DataFrame
  • dict 可以指定每一行或列用什么值填充
  • method: {‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None
  • 在列上操作
    • ffill / pad: 使用前一个值来填充缺失值
    • backfill / bfill :使用后一个值来填充缺失值
  • limit 填充的缺失值个数限制。应该不怎么用
  1. f = pd.DataFrame([[np.nan, 2, np.nan, 0],
  2. [3, 4, np.nan, 1],
  3. [np.nan, np.nan, np.nan, 5],
  4. [np.nan, 3, np.nan, 4]],
  5. columns=list('ABCD'))
  6. >>> df
  7. A B C D
  8. 0 NaN 2.0 NaN 0
  9. 1 3.0 4.0 NaN 1
  10. 2 NaN NaN NaN 5
  11. 3 NaN 3.0 NaN 4
  12.  
  13. # 使用0代替所有的缺失值
  14. >>> df.fillna(0)
  15. A B C D
  16. 0 0.0 2.0 0.0 0
  17. 1 3.0 4.0 0.0 1
  18. 2 0.0 0.0 0.0 5
  19. 3 0.0 3.0 0.0 4
  20.  
  21. # 使用后边或前边的值填充缺失值
  22. >>> df.fillna(method='ffill')
  23. A B C D
  24. 0 NaN 2.0 NaN 0
  25. 1 3.0 4.0 NaN 1
  26. 2 3.0 4.0 NaN 5
  27. 3 3.0 3.0 NaN 4
  28.  
  29. >>>df.fillna(method='bfill')
  30. A B C D
  31. 0 3.0 2.0 NaN 0
  32. 1 3.0 4.0 NaN 1
  33. 2 NaN 3.0 NaN 5
  34. 3 NaN 3.0 NaN 4
  35.  
  36. # Replace all NaN elements in column ‘A', ‘B', ‘C', and ‘D', with 0, 1, 2, and 3 respectively.
  37. # 每一列使用不同的缺失值
  38. >>> values = {'A': 0, 'B': 1, 'C': 2, 'D': 3}
  39. >>> df.fillna(value=values)
  40. A B C D
  41. 0 0.0 2.0 2.0 0
  42. 1 3.0 4.0 2.0 1
  43. 2 0.0 1.0 2.0 5
  44. 3 0.0 3.0 2.0 4
  45.  
  46. #只替换第一个缺失值
  47. >>>df.fillna(value=values, limit=1)
  48. A B C D
  49. 0 0.0 2.0 2.0 0
  50. 1 3.0 4.0 NaN 1
  51. 2 NaN 1.0 NaN 5
  52. 3 NaN 3.0 NaN 4

房价分析:

在此问题中,只有bedroom一列有缺失值,按照此三种方法处理代码为:

  1. # option 1 将含有缺失值的行去掉
  2. housing.dropna(subset=["total_bedrooms"])
  3.  
  4. # option 2 将"total_bedrooms"这一列从数据中去掉
  5. housing.drop("total_bedrooms", axis=1)
  6.  
  7. # option 3 使用"total_bedrooms"的中值填充缺失值
  8. median = housing["total_bedrooms"].median()
  9. housing["total_bedrooms"].fillna(median)

sklearn提供了处理缺失值的 Imputer类,具体的使用教程在这:https://www.jb51.net/article/259441.htm

总结

到此这篇关于Python pandas处理缺失值(dropna、drop、fillna)的文章就介绍到这了,更多相关pandas处理缺失值内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号