python数据预处理练习

2024-09-01 22:58
文章标签 python 数据 练习 预处理

本文主要是介绍python数据预处理练习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[python]  view plain  copy
  1. #ecoding=utf-8  
  2. import math  
  3. import re  
  4. import csv  
  5.   
  6. def fileREAD(fileURL,access):  
  7.     "传入文件路径,返回存储文件内容的二维列表"  
  8.     localArray = []  # 创建一个列表用于存储文件内容  
  9.     csvfile = file(fileURL, access)  
  10.     reader = csv.reader(csvfile)  
  11.     for line in reader:  
  12.         localArray.append(line)  
  13.     csvfile.close()  
  14.     return localArray  
  15.   
  16. def getLine(inList,Line):  
  17.     "获得某一行数据"  
  18.     return inList[Line]  
  19.   
  20. def getRow(inList,Row):  
  21.     "获得某一列数据"  
  22.     listReturn = []  
  23.     for i in inList:  
  24.         listReturn.append(i[Row])  
  25.     return listReturn  
  26.   
  27. def setLine(inList,childList,Line):  
  28.     "设置矩阵某一行数据"  
  29.     inList[Line] = childList  
  30.   
  31. def setRow(inList,chikdList,Row):  
  32.     "设置矩阵的某一列"  
  33.     i = 0  
  34.     for i in range(0,len(chikdList)):  
  35.         inList[i][Row] = chikdList[i]  
  36.   
  37. def addLine(inList,childLine):  
  38.     "给数据矩阵添加一行"  
  39.     inList.append(childLine)  
  40.   
  41. def addRow(inList,childRow):  
  42.     "给数据矩阵添加一列"  
  43.     j = 0  
  44.     for i in inList:  
  45.         i.append(childRow[j])  
  46.         j = j+1  
  47.   
  48. def getAVG(inList):  
  49.     "求数值属性的均值"  
  50.     sumOfList = 0  
  51.     lengOfList = 0  
  52.     for i in inList:  
  53.         if re.match(r'[0-9]+',i):  
  54.             sumOfList = sumOfList + float(i)  
  55.             lengOfList = lengOfList + 1  
  56.         else:  
  57.             continue  
  58.     if lengOfList != 0 :  
  59.         return sumOfList/lengOfList  
  60.     else:  
  61.         return "当前特征无平均值"  
  62.   
  63. def getAVE(inList):  
  64.     "求数值属性的方差"  
  65.     #先求平均数  
  66.     sumOfList = 0  
  67.     lengOfList = 0  
  68.     su = 0  
  69.     for i in inList:  
  70.         if re.match(r'[0-9]+', i):  
  71.             sumOfList = sumOfList + float(i)  
  72.             lengOfList = lengOfList + 1  
  73.         else:  
  74.             continue  
  75.     if lengOfList != 0:  
  76.         avg = sumOfList / lengOfList  
  77.         for j in inList:  
  78.             if re.match(r'[0-9]+',j):  
  79.                 su += (float(j) - avg) ** 2  
  80.             else:  
  81.                 continue  
  82.         return math.sqrt(su)  
  83.     else:  
  84.         return "当前特征无方差"  
  85.   
  86. def average(seq, total=0.0):  
  87.   num = 0  
  88.   for item in seq:  
  89.     total += item  
  90.     num += 1  
  91.   return total / num  
  92.   
  93. def getQUANTILE(inList,inlocaltion):  
  94.     "求数值属性的分位数"  
  95.     if inlocaltion >1 or inlocaltion<0 or inlocaltion == 1:  
  96.         return "输入的分位数数值错误"  
  97.     localLst = []  
  98.     leng = 0  
  99.     for i in inList:  
  100.         if re.match(r'[0-9]+',i):  
  101.             localLst.append(float(i))  
  102.             leng = leng + 1  
  103.         else:  
  104.             continue  
  105.     if leng == 0:  
  106.         return "当前特征不可求中位数"  
  107.     localLst.sort()  
  108.     if inlocaltion == 0.5:  
  109.          if len(localLst)%2 == 1:  
  110.              return localLst[len(localLst)//2]  
  111.          else:  
  112.              return (localLst[len(localLst)//2-1]+localLst[len(localLst)//2])/2.0  
  113.     elif inlocaltion<1 and inlocaltion>=0:  
  114.         return localLst[int(len(localLst)*inlocaltion)]  
  115.   
  116. def fileREAD(fileURL,access):  
  117.     "传入文件路径,返回存储文件内容的二维列表"  
  118.     localArray = []  # 创建一个列表用于存储文件内容  
  119.     csvfile = file(fileURL, access)  
  120.     reader = csv.reader(csvfile)  
  121.     for line in reader:  
  122.         localArray.append(line)  
  123.     csvfile.close()  
  124.     return localArray  
  125.   
  126. def removeNoiseAuto(inList):  
  127.     "利用IRQ识别噪声数据并去除该数据"  
  128.     Q3 = getQUANTILE(inList,0.75)  
  129.     Q1 = getQUANTILE(inList,0.25)  
  130.     IRQ = Q3 - Q1  
  131.     for i in range(1,len(inList),1):  
  132.         if float(inList[i]) - Q3 > 1.5*IRQ or Q1 - float(inList[i]) > 1.5*IRQ:  
  133.             inList[i] = ''  
  134.     return inList  
  135.   
  136. def removeNoiseByThresholdMin(inList,inThresholdMin):  
  137.     "根据最小阈值去除噪声数据去除该数据"  
  138.     for i in range(1, len(inList), 1):  
  139.         if float(inList[i]) < inThresholdMin:  
  140.             inList[i] = ''  
  141.     return inList  
  142.   
  143. def removeNoiseByThresholdMax(inList,inThresholdMax):  
  144.     "根据最大阈值去除噪声数据去除该数据"  
  145.     for i in range(1, len(inList), 1):  
  146.         if float(inList[i]) > inThresholdMax:  
  147.             inList[i] = ''  
  148.     return inList  
  149.   
  150. def autoPaddingByAVG(inList):  
  151.     "利用均值补全缺失值"  
  152.     avg = getAVG(inList)  
  153.     for i in range(1, len(inList), 1):  
  154.         if inList[i] == '':  
  155.             inList[i] = str(avg)  
  156.     return inList  
  157.   
  158. def autoPaddingByMedian(inList):  
  159.     "利用中位数补全缺失值"  
  160.     avg = getQUANTILE(inList,0.5)  
  161.     for i in range(1, len(inList), 1):  
  162.         if inList[i] == '':  
  163.             inList[i] = str(avg)  
  164.     return inList  
  165.   
  166. def binningWidth(inList,width):  
  167.     "数据离散化:等宽分箱"  
  168.     dic = {}  
  169.     for i in range(1,len(inList)):  
  170.         dic[i] =float(inList[i])  
  171.     dict = sorted(dic.iteritems(), key=lambda d: d[1], reverse= False)  # 先将列表按value排序  
  172.     dictList = []  # 将排序后元素赋值给一个列表,用于存储K-V对  
  173.     for varlo in dict:  
  174.         dictList.append(list(varlo))  
  175.     i = 0  # 用于记录每个箱开始位置  
  176.     j = 0  #用于记录每个箱结束位置  
  177.     innerList = []  
  178.     for i in range(0, len(dictList)):  
  179.         if dictList[i][1] - dictList[j][1] > width:  
  180.             avg = average(innerList)  
  181.             for k in range(j, i, 1):  
  182.                 dictList[k][1] = avg  
  183.             innerList = []  
  184.             j = i  
  185.         innerList.append(dictList[i][1])  
  186.         if (i == len(dictList)-1):  
  187.             avg = average(innerList)  
  188.             for k in range(j, i, 1):  
  189.                 dictList[k][1] = avg  
  190.             innerList = []  
  191.             dictList[i][1] = avg  
  192.   
  193.     dic1 = {}  
  194.     for i in range(0, len(dictList)):  
  195.         dic1[dictList[i][0]] = dictList[i][1]  
  196.     ad = sorted(dic1.iteritems(), key=lambda d: d[0], reverse=False)  # 先将列表按KEY排序  
  197.     for i in range(0, len(ad)):  
  198.         inList[i + 1] = ad[i][1]  
  199.     return inList  
  200.   
  201. def binningDeep(inList,deep1):  
  202.     "数据离散化:等频分箱"  
  203.     deep = deep1 -1  
  204.     dic = {}  
  205.     for i in range(1,len(inList)):  
  206.         dic[i] =float(inList[i])  
  207.     dict = sorted(dic.iteritems(), key=lambda d: d[1], reverse= False)  # 先将列表按value排序  
  208.     dictList = []  # 将排序后元素赋值给一个列表,用于存储K-V对  
  209.     for varlo in dict:  
  210.         dictList.append(list(varlo))  
  211.     innerList = []  
  212.     for i in range(0,deep):  #为了排除0的干扰,首先处理掉deep个元素  
  213.         innerList.append(dictList[i][1])  
  214.     for i in range(deep, len(dictList)):  
  215.         if i % deep == 0:  
  216.             avg = average(innerList)  
  217.             for j in range(i-deep,i):  
  218.                 dictList[j][1] = avg  
  219.             innerList = []  
  220.         innerList.append(dictList[i][1])  
  221.         if i == len(dictList)-1:  
  222.             avg = average(innerList)  
  223.             for j in range((i+1)/deep*deep,i+1):  
  224.                 dictList[j][1] = avg  
  225.   
  226.     dic1 = {}  
  227.     for i in range(0, len(dictList)):  
  228.         dic1[dictList[i][0]] = dictList[i][1]  
  229.     ad = sorted(dic1.iteritems(), key=lambda d: d[0], reverse= False)  # 先将列表按KEY排序  
  230.     for i in range(0,len(ad)):  
  231.         inList[i+1] = ad[i][1]  
  232.     return inList  
  233.   
  234. def oneHot(inList,Row):  
  235.     "对输入数据矩阵的某一列使用oneHot编码"  
  236.     rowList0 = getRow(inList,Row)  
  237.     rowHead = rowList0[0]  
  238.     rowList = []  
  239.     for i in range(1,len(rowList0)):  
  240.         rowList.append(rowList0[i])  
  241.     rowmsg = {}  
  242.     j = 0  
  243.     for i in rowList:  
  244.         if rowmsg.has_key(i):  
  245.             rowmsg[i] = rowmsg[i] + 1  
  246.         else:  
  247.             rowmsg[i] = 1  
  248.     for i in rowmsg.keys():  
  249.         addList = []  
  250.         addList.append(i)  
  251.         for j in rowList:  
  252.             if j == i:  
  253.                 addList.append('1')  
  254.             else:  
  255.                 addList.append('0')  
  256.         addRow(inList,addList)  
  257.     for i in inList:  
  258.         print i  
  259.   
  260. def  minMax(inList):  
  261.     "最大最小归一化"  
  262.     innerList = []  
  263.     for i in range(1,len(inList)):  
  264.         if re.match(r'[0-9]+', inList[i]):  
  265.             innerList.append(float(inList[i]))  
  266.     maxvalue = max(innerList)  
  267.     minvalue = min(innerList)  
  268.   
  269.     for i in range(1,len(inList)):  
  270.         if re.match(r'[0-9]+', inList[i]):  
  271.             a = (float(inList[i])-minvalue)/(maxvalue - minvalue)  
  272.             b = "%.4f" %a  
  273.             inList[i] = str(b)  
  274.     return inList  
  275.   
  276. def  zScore(inList):  
  277.     "zScore归一化"  
  278.     print inList  
  279.     u = getAVG(inList)  
  280.     ave = getAVE(inList)  
  281.     stand = math.sqrt(ave)  
  282.     for i in range(1,len(inList)):  
  283.         if re.match(r'[0-9]+', inList[i]):  
  284.             a = (float(inList[i])-u)/stand  
  285.             b = "%.4f" % a  
  286.             inList[i] = str(b)  
  287.     return inList  
  288.   
  289. def similarityDistance(inList1,inList2,n):  
  290.     "距离相似度"  
  291.     sum = 0  
  292.     for i in range(1,len(inList1)):  
  293.        sum = sum + abs(float(inList1[i])-float(inList2[i])) ** n  
  294.     a = float(1)/2  
  295.     return pow(sum,a)  
  296.   
  297. def similaritySim(inList1,inList2):  
  298.     "余弦相似度计算"  
  299.     sum = 0  
  300.     for i in range(1,len(inList1)):  
  301.         sum = sum + float(inList1[i])*float(inList2[i])  
  302.     sum1 = 0  
  303.     sum2 = 0  
  304.     for i in range(1,len(inList1)):  
  305.         sum1 = sum1 + float(inList1[i])**2  
  306.     for i in range(1, len(inList2)):  
  307.         sum2 = sum2 + float(inList2[i]) ** 2  
  308.   
  309.     return sum/(math.sqrt(sum1)*math.sqrt(sum2))  
  310.   
  311. fileInput = fileREAD("D:\\PythonWorkSpace\\ExternalFile\\train.csv","r")  
  312.   
  313. # #获得某一行数据  
  314. # print getLine(fileInput,1)  
  315. #  
  316. # #获得某一列数据  
  317. # print getRow(fileInput,0)  
  318.   
  319. # #设置某一行数据  
  320. # print "设置前:"  
  321. # print getLine(fileInput,1)  
  322. # setLine(fileInput,getLine(fileInput,2),1)  
  323. # print "设置后:"  
  324. # print getLine(fileInput,1)  
  325.   
  326. # #设置某一列数据  
  327. # print "设置前:"  
  328. # print getRow(fileInput,1)  
  329. # setRow(fileInput,getRow(fileInput,2),1)  
  330. # print "设置后:"  
  331. # print getRow(fileInput,1)  
  332.   
  333. # #均值  
  334. # print getAVG(getRow(fileInput,9))  
  335.   
  336. # #方差  
  337. # print getAVE(getRow(fileInput,9))  
  338.   
  339. # #分位数  
  340. # print getQUANTILE(getRow(fileInput,9),0.5)  
  341.   
  342. # #噪声数据过滤1  
  343. # print removeNoiseAuto(getRow(fileInput,1))  
  344. #  
  345. # #噪声数据过滤2  
  346. # print removeNoiseByThresholdMin(getRow(fileInput,0),10)  
  347. #  
  348. # #噪声数据过滤3  
  349. # print removeNoiseByThresholdMax(getRow(fileInput,0),10)  
  350.   
  351. # #缺失值补全1  
  352. # print autoPaddingByAVG(getRow(fileInput,0))  
  353. #  
  354. # #缺失值补全2  
  355. # print autoPaddingByMedian(getRow(fileInput,0))  
  356.   
  357. # #等宽分箱  
  358. # print binningWidth(getRow(fileInput,0),3)  
  359. #  
  360. # #等频分箱  
  361. # print binningDeep(getRow(fileInput,0),3)  
  362.   
  363. # #ONE-HOT编码  
  364. # oneHot(fileInput,1)  
  365. # for i in fileInput:  
  366. #     print i  
  367.   
  368. # #最大最小归一化  
  369. # print minMax(getRow(fileInput,0))  
  370. #  
  371. # #zScore归一化  
  372. # print zScore(getRow(fileInput,0))  
  373.   
  374. # #距离相似度  
  375. # print similarityDistance(getRow(fileInput,0),getRow(fileInput,0),2)  
  376.   
  377. # # 余弦相似度计算  
  378. # print similaritySim(getRow(fileInput,0),getRow(fileInput,1))  



原文地址:http://blog.csdn.NET/u012155582/article/details/52051776

这篇关于python数据预处理练习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1128283

相关文章

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

Python中文件读取操作漏洞深度解析与防护指南

《Python中文件读取操作漏洞深度解析与防护指南》在Web应用开发中,文件操作是最基础也最危险的功能之一,这篇文章将全面剖析Python环境中常见的文件读取漏洞类型,成因及防护方案,感兴趣的小伙伴可... 目录引言一、静态资源处理中的路径穿越漏洞1.1 典型漏洞场景1.2 os.path.join()的陷

Python数据分析与可视化的全面指南(从数据清洗到图表呈现)

《Python数据分析与可视化的全面指南(从数据清洗到图表呈现)》Python是数据分析与可视化领域中最受欢迎的编程语言之一,凭借其丰富的库和工具,Python能够帮助我们快速处理、分析数据并生成高质... 目录一、数据采集与初步探索二、数据清洗的七种武器1. 缺失值处理策略2. 异常值检测与修正3. 数据

Python中bisect_left 函数实现高效插入与有序列表管理

《Python中bisect_left函数实现高效插入与有序列表管理》Python的bisect_left函数通过二分查找高效定位有序列表插入位置,与bisect_right的区别在于处理重复元素时... 目录一、bisect_left 基本介绍1.1 函数定义1.2 核心功能二、bisect_left 与

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”

VSCode设置python SDK路径的实现步骤

《VSCode设置pythonSDK路径的实现步骤》本文主要介绍了VSCode设置pythonSDK路径的实现步骤,包括命令面板切换、settings.json配置、环境变量及虚拟环境处理,具有一定... 目录一、通过命令面板快速切换(推荐方法)二、通过 settings.json 配置(项目级/全局)三、

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

Python struct.unpack() 用法及常见错误详解

《Pythonstruct.unpack()用法及常见错误详解》struct.unpack()是Python中用于将二进制数据(字节序列)解析为Python数据类型的函数,通常与struct.pa... 目录一、函数语法二、格式字符串详解三、使用示例示例 1:解析整数和浮点数示例 2:解析字符串示例 3:解

Python程序打包exe,单文件和多文件方式

《Python程序打包exe,单文件和多文件方式》:本文主要介绍Python程序打包exe,单文件和多文件方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python 脚本打成exe文件安装Pyinstaller准备一个ico图标打包方式一(适用于文件较少的程