"Python代码:如何删除数据中的异常值"\n使用Python代码从数据中删除异常值,包括使用标准差和箱线图两种方法。文章包含详细的代码示例和解释,帮助您有效地处理异常数据。\n\n方法1:使用标准差来检测异常值\n\npython\nimport numpy as np\n\ndef remove_outliers(data):\n mean = np.mean(data)\n std = np.std(data)\n threshold = 3 * std\n filtered_data = [x for x in data if (mean - threshold < x < mean + threshold)]\n return filtered_data\n\ndata = [1, 2, 3, 4, 5, 1000] # 示例数据\nfiltered_data = remove_outliers(data)\nprint(filtered_data)\n\n\n方法2:使用箱线图来检测异常值\n\npython\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef remove_outliers(data):\n q1 = np.percentile(data, 25)\n q3 = np.percentile(data, 75)\n iqr = q3 - q1\n threshold = 1.5 * iqr\n filtered_data = [x for x in data if (q1 - threshold < x < q3 + threshold)]\n return filtered_data\n\ndata = [1, 2, 3, 4, 5, 1000] # 示例数据\nfiltered_data = remove_outliers(data)\nprint(filtered_data)\n\n\n这些代码会从给定的数据中删除所有异常值,并返回过滤后的数据。


原文地址: https://www.cveoy.top/t/topic/pOp9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录