python如何去除异常值和缺失值的插值

1.使用箱型法去除异常值:

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib as plt
  4. import os
  5. data = pd.read_excel('try.xls', header=0)
  6. # print(data.shape)
  7. # print(data.head(10))
  8. # print(data.describe())
  9. neg_list = ['位移']
  10. print("(1)数据的行数为:")
  11. R = data.shape[0]
  12. print(R)
  13. print("(2)小于或大于阈值的数据提取:")
  14. for item in neg_list:
  15. neg_item = data[item]<2000
  16. print(item + '小于2000的有' + str(neg_item.sum()) + '个')
  17. print("(3)异常值的个数:")
  18. for item in neg_list:
  19. iqr = data[item].quantile(0.75) - data[item].quantile(0.25)
  20. q_abnormal_L = data[item] < data[item].quantile(0.25) - 1.5 * iqr
  21. q_abnormal_U = data[item] > data[item].quantile(0.75) + 1.5 * iqr
  22. print(item + '中有' + str(q_abnormal_L.sum() + q_abnormal_U.sum()) + '个异常值')
  23. print("(4)箱型图确定上下限:")
  24. for item in neg_list:
  25. iqr = data[item].quantile(0.75) - data[item].quantile(0.25)
  26. Too_small = data[item].quantile(0.25) - 1.5 * iqr
  27. Too_big = data[item].quantile(0.25) + 1.5 * iqr
  28. print("下限是", Too_small)
  29. print("上限是", Too_big )
  30. print("(5)所有数据为:")
  31. a = []
  32. for i in neg_list:
  33. a.append(data[i])
  34. print(a)
  35. print("(6)所有正常数据:")
  36. b = []
  37. j = 0
  38. while j < R:
  39. if (a[0][j] > Too_small):
  40. if (a[0][j] < Too_big):
  41. b.append(a[0][j])
  42. j += 1
  43. print(b)
  44. print("(7)所有异常数据:")
  45. c = []
  46. i = 0
  47. while i < R:
  48. if (a[0][i] < Too_small or a[0][i] > Too_big):
  49. c.append(a[0][i])
  50. a[0][i] = None
  51. i +=1
  52. print(c)
  53. print("(8)把所有异常数据删除后:")
  54. print(a)
  55. print("(9)所有数据处理后输出:")
  56. d = []
  57. k = 0
  58. while k < R:
  59. d.append(a[0][k])
  60. k +=1
  61. print(d)
  62. df = pd.DataFrame(d,columns= ['位移'])
  63. df.to_excel("try_result.xls")

2.拉格朗日插值:

  1. import os
  2. import pandas as pd
  3. import numpy as np
  4. from scipy.interpolate import lagrange
  5. import matplotlib.pyplot as plt
  6. plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
  7. plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
  8. # 数据的读取
  9. data = pd.read_excel('try.xls', header=0)
  10. neg_list = ['位移']
  11. # 数据的行数
  12. R = data.shape[0]
  13. # 异常数据的个数
  14. for item in neg_list:
  15. iqr = data[item].quantile(0.75) - data[item].quantile(0.25)
  16. q_abnormal_L = data[item] < data[item].quantile(0.25) - 1.5 * iqr
  17. q_abnormal_U = data[item] > data[item].quantile(0.75) + 1.5 * iqr
  18. # print(item + '中有' + str(q_abnormal_L.sum() + q_abnormal_U.sum()) + '个异常值')
  19. # 确定数据上限和下限
  20. for item in neg_list:
  21. iqr = data[item].quantile(0.75) - data[item].quantile(0.25)
  22. Too_small = data[item].quantile(0.25) - 1.5 * iqr
  23. Too_big = data[item].quantile(0.25) + 1.5 * iqr
  24. data[u'位移'][(data[u'位移']<Too_small) | (data[u'位移']>Too_big)] = None #过滤异常值,将其变为空值
  25. #s为列向量,n为被插值位置,k为取前后的数据个数
  26. def ployinter(s,n,k=5):
  27. y = s[list(range(n-k,n)) + list(range(n+1,n+1+k))]
  28. y = y[y.notnull()] #剔除空值
  29. return lagrange(y.index,list(y))(n)
  30. #逐个元素判断是否需要插值
  31. for i in data.columns:
  32. for j in range(len(data)):
  33. if(data[i].isnull())[j]:
  34. data[i][j] = ployinter(data[i],j)
  35. # print(data[u'位移'])
  36. # 输出拉格朗日插值后的数据
  37. data.to_excel("try_result.xls")
  38. # 把表格列数据调整为arr,arr为修改后的数据
  39. print("拉格朗日插值后的数据:")
  40. d = []
  41. k = 0
  42. while k < R:
  43. d.append(data[u'位移'][k])
  44. k +=1
  45. # print(d)
  46. arr = np.array(d)
  47. print(arr)
  48. # 输出图像
  49. x = np.arange(len(d))
  50. plt.plot(x,d,'b-',label="one", marker='*',markersize=4,linewidth=1) # b代表blue颜色 -代表直线
  51. plt.title('位移曲线')
  52. plt.legend(loc='upper left',bbox_to_anchor=(1.0,1.0))
  53. # 直接更改X轴坐标数
  54. # plt.xticks((0,1,2,3,4,5,6,7,8),('0', '1', '2', '3', '4', '5', '6', '7', '8'))
  55. plt.xlabel('时间/h')
  56. plt.ylabel('位移/mm')
  57. #plt.grid(x1)
  58. plt.show

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

def Fun(p, x): # 定义拟合函数形式
a1, a2, a3 , a4 = p
return a1 x ** 3 + a2 x * 2 + a3 x + a4

def error(p, x, y): # 拟合残差
return Fun(p, x) - y

def main():
x = np.linspace(1, 31, 31) # 创建时间序列
data = pd.read_excel(‘try.xls’, header=0)
y = data[u’位移’]
p0 = [0.1, -0.01, 100, 1000] # 拟合的初始参数设置
para = leastsq(error, p0, args=(x, y)) # 进行拟合
y_fitted = Fun(para[0], x) # 画出拟合后的曲线

  1. plt.figure
  2. plt.plot(x, y, 'r', label='Original curve')
  3. plt.plot(x, y_fitted, '-b', label='Fitted curve')
  4. plt.legend()
  5. plt.show()
  6. print(para[0])
  7. main()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

def Fun(p, x): # 定义拟合函数形式
a1, a2, a3 , a4 = p
return a1 x ** 3 + a2 x * 2 + a3 x + a4

def error(p, x, y): # 拟合残差
return Fun(p, x) - y

def main():
x = np.linspace(1, 31, 31) # 创建时间序列
data = pd.read_excel(‘try.xls’, header=0)
y = data[u’位移’]
p0 = [0.1, -0.01, 100, 1000] # 拟合的初始参数设置
para = leastsq(error, p0, args=(x, y)) # 进行拟合
y_fitted = Fun(para[0], x) # 画出拟合后的曲线

  1. plt.figure
  2. plt.plot(x, y, 'r', label='Original curve')
  3. plt.plot(x, y_fitted, '-b', label='Fitted curve')
  4. plt.legend()
  5. plt.show()
  6. print(para[0])
  7. main()

3.数据拟合:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

  1. def Fun(p, x): # 定义拟合函数形式
  2. a1, a2, a3 , a4 = p
  3. return a1 * x ** 3 + a2 * x ** 2 + a3 * x + a4
  4. def error(p, x, y): # 拟合残差
  5. return Fun(p, x) - y
  6. def main():
  7. x = np.linspace(1, 31, 31) # 创建时间序列
  8. data = pd.read_excel('try.xls', header=0)
  9. y = data[u'位移']
  10. p0 = [0.1, -0.01, 100, 1000] # 拟合的初始参数设置
  11. para = leastsq(error, p0, args=(x, y)) # 进行拟合
  12. y_fitted = Fun(para[0], x) # 画出拟合后的曲线
  13. plt.figure
  14. plt.plot(x, y, 'r', label='Original curve')
  15. plt.plot(x, y_fitted, '-b', label='Fitted curve')
  16. plt.legend()
  17. plt.show()
  18. print(para[0])
  19. if __name__ == '__main__':
  20. main()

4.输出图像:
import pandas as pd

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
  4. plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
  5. jiaodu = ['0', '15', '30', '15', '60', '75', '90', '105', '120']
  6. x = range(len(jiaodu))
  7. y = [85.6801, 7.64586, 86.0956, 159.229, 179.534, 163.238, 96.4436, 10.1619, 90.9262,]
  8. #plt.figure(figsize=(10, 6))
  9. plt.plot(x,y,'b-',label="1", marker='*',markersize=7,linewidth=3) # b代表blue颜色 -代表直线
  10. plt.title('各个区域亮度变化')
  11. plt.legend(loc='upper left',bbox_to_anchor=(1.0,1.0))
  12. plt.xticks((0,1,2,3,4,5,6,7,8),('0', '15', '30', '15', '60', '75', '90', '105', '120'))
  13. plt.xlabel('角度')
  14. plt.ylabel('亮度')
  15. #plt.grid(x1)
  16. plt.show()

到此这篇关于python如何去除异常值和缺失值的插值的文章就介绍到这了,更多相关python去除异常值和缺失值内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

更多相关文章

  1. Android点赞动画效果 ,点赞后加一,2种方法,①补间动画②位移动画
  2. Android(安卓)Property Animation属性动画初识:位移translation(3)
  3. Android(安卓)自定义动画 单个View平面位移以及一组View轮回旋转
  4. android 模拟器 得到GPS
  5. Java,Android(安卓)Integer和byte的相互转换,Java Android给定范围
  6. Android消息提示框Toast
  7. Android开发如何设置文字阴影
  8. 【特效】【自定义控件】关键字飘飞效果
  9. Android改变Spinner弹出框的位置

随机推荐

  1. 如何修改JTextField (Swing)以显示在用户
  2. Java_io体系之BufferedWriter、BufferedR
  3. 黑马程序员——java高新技术(下)
  4. (Java)出现/消失JPanel中的JLabel仅在调整
  5. 在Java中,使用DefaultSelenium对象在selen
  6. Eclipse Java开发环境的搭建
  7. java通过映射取得方法对一个类的变量进行
  8. JavaScript基础——变量、作用域和内存问
  9. 如何让我的基本SWT应用程序在Mac OS X 10
  10. 老农过河问题