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操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

python中列表应用和扩展性实用详解

《python中列表应用和扩展性实用详解》文章介绍了Python列表的核心特性:有序数据集合,用[]定义,元素类型可不同,支持迭代、循环、切片,可执行增删改查、排序、推导式及嵌套操作,是常用的数据处理... 目录1、列表定义2、格式3、列表是可迭代对象4、列表的常见操作总结1、列表定义是处理一组有序项目的

python运用requests模拟浏览器发送请求过程

《python运用requests模拟浏览器发送请求过程》模拟浏览器请求可选用requests处理静态内容,selenium应对动态页面,playwright支持高级自动化,设置代理和超时参数,根据需... 目录使用requests库模拟浏览器请求使用selenium自动化浏览器操作使用playwright

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

Python极速搭建局域网文件共享服务器完整指南

《Python极速搭建局域网文件共享服务器完整指南》在办公室或家庭局域网中快速共享文件时,许多人会选择第三方工具或云存储服务,但这些方案往往存在隐私泄露风险或需要复杂配置,下面我们就来看看如何使用Py... 目录一、android基础版:HTTP文件共享的魔法命令1. 一行代码启动HTTP服务器2. 关键参

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Python获取浏览器Cookies的四种方式小结

《Python获取浏览器Cookies的四种方式小结》在进行Web应用程序测试和开发时,获取浏览器Cookies是一项重要任务,本文我们介绍四种用Python获取浏览器Cookies的方式,具有一定的... 目录什么是 Cookie?1.使用Selenium库获取浏览器Cookies2.使用浏览器开发者工具

C语言进阶(预处理命令详解)

《C语言进阶(预处理命令详解)》文章讲解了宏定义规范、头文件包含方式及条件编译应用,强调带参宏需加括号避免计算错误,头文件应声明函数原型以便主函数调用,条件编译通过宏定义控制代码编译,适用于测试与模块... 目录1.宏定义1.1不带参宏1.2带参宏2.头文件的包含2.1头文件中的内容2.2工程结构3.条件编

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库