首页 > 编程语言 >python数据分析与挖掘实战第八章

python数据分析与挖掘实战第八章

时间:2023-03-14 16:22:41浏览次数:41  
标签:数据分析 sort plt python list 第八章 supportData csv data

#8-1
import numpy as np
import pandas as pd

inputfile = 'data4/GoodsOrder.csv'
data = pd.read_csv(inputfile,encoding='gbk')
data.info()

data = data['id']
description = [data.count(),data.min(),data.max()]
description =pd.DataFrame(description,index=['Count','Min','Max']).T
print('3107描述性统计结果:\n',np.round(description))

#8-2
import pandas as pd
inputfile = 'data4/GoodsOrder.csv'
data = pd.read_csv(inputfile,encoding='gbk')
group = data.groupby(['Goods']).count().reset_index()# 对商品进行分类汇总
sorted = group.sort_values('id',ascending=False)
print('3107销量排行前10商品的销量:\n',sorted[:10])

#画条形图展示销量排行前10的商品销量
import matplotlib.pyplot as plt
x = sorted[:10]['Goods']
y = sorted[:10]['id']
plt.figure(figsize=(8,4))
plt.barh(x,y)
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.xlabel('销量')
plt.ylabel('商品类别')
plt.title('3107商品的销量TOP10')
plt.savefig('data4/top10.png')
plt.show()

# 销量排行前10的商品销量占比
data_nums = data.shape[0]
for idnex, row in sorted[:10].iterrows():
    print(row['Goods'],row['id'],row['id']/data_nums)

#8-3
import pandas as pd
inputfile1 = 'data4/GoodsOrder.csv'
inputfile2 = 'data4/GoodsTypes.csv'
data= pd.read_csv(inputfile1,encoding='gbk')
types = pd.read_csv(inputfile2,encoding='gbk')

group = data.groupby(['Goods']).count().reset_index()
sort = group.sort_values('id',ascending=False).reset_index()
data_nums = data.shape[0]    # 总量
del sort['index']

sort_links = pd.merge(sort,types)   # 根据type合并两个datafreame

#根据类别求和,每个商品类别的总量,并排序
sort_link = sort_links.groupby(['Types']).sum().reset_index()
sort_link = sort_link.sort_values('id',ascending=False).reset_index()
del sort_link['index']     # 删除“index”列

# 求百分比,然后更换列名,最后输出列文件
sort_link['count'] = sort_link.apply(lambda line:line['id']/data_nums,axis=1)
sort_link.rename(columns={'count':'percent'},inplace=True)
print('3107各类别商品的销量及其占比:\n',sort_link)
outfile1 = 'data4/percent.csv'
sort_link.to_csv(outfile1, index=False, header=True, encoding='gbk')

#画饼图展示每类商品的销量占比
import matplotlib.pyplot as plt
data = sort_link['percent']
labels = sort_link['Types']
plt.figure(figsize=(8,6))
plt.pie(data,labels=labels, autopct='%1.2f%%')
plt.rcParams['font.sans-serif'] ='SimHei'
plt.title('3107每类商品销量占比')
plt.savefig('data4/persent.png')
plt.show()

#8-4
# 先筛选“非酒精饮料”类型的商品,然后求百分比,然后输出结果到文件
selected = sort_links.loc[sort_links['Types'] =='非酒精饮料']
child_nums = selected['id'].sum()     #对所有的“非酒精饮料”求和
selected['child_percent'] = selected.apply(lambda line:line['id']/child_nums,
                                           axis=1)   # 求百分比
selected.rename(columns={'id':'count'},inplace=True)     
print('3107非酒精饮料内部商品的销量及其占比: \n',selected)
outfile2 ='data4/child_percent.csv'
sort_link.to_csv(outfile2,index=False,header=True,encoding='gbk')

# 画饼图展示非酒精饮品内部各商品的销量占比
import matplotlib.pyplot as plt
data = selected['child_percent']
labels = selected['Goods']
plt.figure(figsize=(8,6))
explode = (0.02,0.03,0.04,0.05,0.06,0.07,0.08,0.08,0.3,0.1,0.3) #设置每一块分割出的间隙大小
plt.pie(data,explode=explode,labels=labels,autopct='%1.2f%%',
        pctdistance=1.1,labeldistance=1.2)
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.title("3107非酒精饮料内部各商品的销量占比")
plt.axis('equal')
plt.savefig('data4/child_persent.png')
plt.show()

#8-5
import pandas as pd
inputfile = 'data4/GoodsOrder.csv'
data = pd.read_csv(inputfile,encoding='gbk')

data['Goods'] = data['Goods'].apply(lambda x:','+x)
data = data.groupby('id')['Goods'].sum().reset_index()

data['Goods'] = data['Goods'].apply(lambda x:[x[1:]])
data_list = list(data['Goods'])

data_translation = []
for i in data_list:
    p = i[0].split(',')
    data_translation.append(p)

print('数据转换结果的前5个元素: \n',data_translation[0:5])

  1 #8-6
  2 from numpy import *
  3 
  4 def loadDataSet():
  5     return [['a','c','e'],['b','d'],['b','c'],['a','b','c','d'],
  6             ['a','b'],['b','c'],['a','b'],['a','b','c','e'],
  7             ['a','b','c'],['a','c','e']]
  8 
  9 def createC1(dataSet):
 10     C1 = []
 11     for transaction in dataSet:
 12         for item in transaction:
 13             if not [item] in C1:
 14                 C1.append([item])
 15     C1.sort()
 16     #映射为frozenset唯一性的,可使用其构造字典
 17     return list(map(frozenset,C1))
 18 
 19 # 从候选K项集到频繁K项集 (支持度计算 )
 20 def scanD(D,Ck,minSupport):
 21     ssCnt = {}
 22     for tid in D:                    #遍历数据集
 23         for can in Ck:               #遍历候选项
 24             if can.issubset(tid):    #判断候选项中是否含数据集的各项
 25                 if not can in ssCnt:
 26                     ssCnt[can] = 1   # 不含设为1
 27                 else:
 28                     ssCnt[can] += 1  #有则计数加1
 29     numItems = float(len(D))              # 数据集大小
 30     retList = []                          # L1初始化
 31     supportData = {}                      #记录候选项中各个数据的支持度
 32     for key in ssCnt:
 33         support = ssCnt[key] / numItems   # 计算支持度
 34         if support >= minSupport:
 35             retList.insert(0,key)         # 满足条件加入L1中
 36             supportData[key] = support
 37     return retList,supportData
 38 
 39 def calSupport(D,Ck,min_support):
 40     dict_sup ={}
 41     for i in D:
 42         for j in Ck:
 43             if j.issubset(i):
 44                 if not j in dict_sup:
 45                     dict_sup[j] = 1
 46                 else:
 47                     dict_sup[j] += 1
 48     sumCount = float(len(D))
 49     supportData = {}
 50     relist = []
 51     for i in dict_sup:
 52         temp_sup = dict_sup[i] / sumCount
 53         if temp_sup >= min_support:
 54             relist.append(i)
 55             #此处可设置返回全部的支持度数据(或者频繁项集的支持度数据)
 56             supportData[i]= temp_sup
 57     return relist,supportData
 58 
 59 #改进剪枝算法
 60 def aprioriGen(Lk,k):
 61     retList = []
 62     lenLk =len(Lk)
 63     for i in range(lenLk):
 64         for j in range(i + 1,lenLk):#两两组合遍历
 65             L1 = list(Lk[i])[:k - 2]
 66             L2 = list(Lk[j])[:k - 2]
 67             L1.sort()
 68             L2.sort()
 69             if L1 == L2:   #前k-1项相等,则可相乘,这样可防止重复项出现
 70                 # 进行剪枝 (a1为k项集中的一个元素,b为它的所有k-1项子集 )
 71                 a = Lk[i] | Lk[j]  # a为frozenset()集合
 72                 a1 = list(a)
 73                 b = []
 74                 # 遍历取出每一个元素,转换为set,依次从a1中剔除该元素,并加入到b中
 75                 for q in range(len(a1)):
 76                     t= [a1[q]]
 77                     tt = frozenset(set(a1) - set(t))
 78                     b.append(tt)
 79                 t=0
 80                 for w in b:
 81                     #当b(即所有k-1项子集)都是Lk(频繁的)的子集,则保留,否则删除
 82                     if w in Lk:
 83                         t += 1
 84                 if t == len(b):
 85                     retList.append(b[0] | b[1])
 86     return retList
 87 
 88 def apriori(dataSet,minSupport=0.2):
 89     #前3条语句是对计算查找单个元素中的频繁项集
 90     C1 = createC1(dataSet)
 91     D = list(map(set,dataSet))    # 使用list()转换为列表
 92     L1,supportData = calSupport(D,C1,minSupport)
 93     L = [L1]                      # 加列表框,使得1项集为一个单独元素
 94     k=2
 95     while (len(L[k - 2]) > 0):    # 是否还有候选集
 96         Ck = aprioriGen(L[k - 2],k)
 97         Lk, supK = scanD(D, Ck, minSupport)   # scan DB to get Lk
 98         supportData.update(supK)  # 把supk的键值对添加到supportData里
 99         L.append(Lk)              #L最后一个值为空集
100         k += 1
101     del L[-1]                     #删除最后一个空集
102     return L,supportData          # L为频繁项集,为一个列表,1,2,3项集分别为一个元素
103 
104 # 生成集合的所有子集
105 def getSubset(fromList,toList):
106     for i in range(len(fromList)):
107         t = [fromList[i]]
108         tt = frozenset(set(fromList) - set(t))
109         if not tt in toList:
110             toList.append(tt)
111             tt = list(tt)
112             if len(tt) > 1:
113                 getSubset(tt,toList)
114 
115 def calcConf(freqSet,H,supportData,ruleList,minConf=0.7):
116     for conseq in H:    # 遍历H中的所有项集并计算它们的可信度值
117         conf = supportData[freqSet] / supportData[freqSet - conseq]  #可信度计算,结合支持度数据
118         # 提升度lift计算lift = p(a & b) / p(a)*p(b)
119         lift = supportData[freqSet] / (supportData[conseq] * supportData [freqSet - conseq])
120         
121         if conf >= minConf and lift > 1:
122             print(freqSet - conseq,'-->',conseq,'支持度', round(supportData[freqSet],6),
123                   '置信度:',round(conf,6),'lift值为:',round(lift,6))
124             ruleList.append((freqSet - conseq,conseq, conf))
125 
126 # 生成规则
127 def gen_rule(L,supportData,minConf=0.7):
128     bigRuleList = []
129     for i in range(1,len(L)):        # 从二项集开始计算
130         # 求该三项集的所有非空子集,1项集,2项集,直到K-1项集,用H1表示,为list类型,里面为frozenset类型,
131         for freqSet in L[i]:         # freqSet为所有的k项集
132             H1 = list(freqSet)
133             all_subset = []# 生成所有的子集
134             getSubset(H1, all_subset)
135             calcConf(freqSet, all_subset, supportData, bigRuleList, minConf)
136     return bigRuleList
137 
138 if __name__ == '__main__':
139     dataSet = data_translation
140     L, supportData = apriori(dataSet, minSupport=0.02)
141     rule = gen_rule(L,supportData,minConf=0.35)

 

标签:数据分析,sort,plt,python,list,第八章,supportData,csv,data
From: https://www.cnblogs.com/pcr-2020310143107/p/17215303.html

相关文章

  • Python+ChatGPT制作一个AI实用百宝箱
    ChatGPT最近在互联网掀起了一阵热潮,其高度智能化的功能能够给我们现实生活带来诸多的便利,可以帮助你写文章、写报告、写周报、做表格、做策划甚至还会写代码。只要与文字......
  • python发送邮件
    importsmtplibfromemail.headerimportHeaderfromemail.mime.textimportMIMETextfromemail.mime.multipartimportMIMEMultipartMAIL={"from":'2547......
  • 窗口的python代码实现
    importtkinterfromtkinterimport*window=tkinter.Tk()window.geometry('1000x800+300+300')window.title('SSH连接器')window.config(bg='grey')label=tkinter.Label(w......
  • [python]运行脚本报错:ModuleNotFoundError: No module named 'bs4'
    [python]运行脚本报错:ModuleNotFoundError:Nomodulenamed'bs4' >pythonmain.py Traceback(mostrecentcalllast):File"main.py",line3,in<module>from......
  • Pcd可视化_根据 intensity 为点云着色_open3d-python
    反射强度据激光测量原理得到的点云,包括三维坐标(XYZ)和激光反射强度(Intensity)。根据摄影测量原理得到的点云,包括三维坐标(XYZ)和颜色信息(RGB)取值范围有0~255和0~6......
  • python获取用户登录ip
    importsocketdefip_check():  s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)  s.connect(('8.8.8.8',80))  ip=s.getsockname()[0]  ......
  • python 爬虫ip代理
    新建proxy_list.txt文本,一行一个ip代理ip地址,必要情况下可以加上端口号importrequestsurl='www.920vip.net'headers={'User-Agent':"Mozilla/5.0(WindowsNT6.1......
  • Python的namedtuple使用详解
    namedtuple又名具名元组,因为普通元组的局限性,不能为元组的数据进行命名,所以我们并不知道一个元组所要表达的意义,所以在这里引入了collections.namedtuple这个工厂函数,来构......
  • 界面控件DevExtreme的Pivot Grid组件——轻松实现多维数据分析
    DevExtreme拥有高性能的HTML5/JavaScript小部件集合,使您可以利用现代Web开发堆栈(包括React,Angular,ASP.NETCore,jQuery,Knockout等)构建交互式的Web应用程序,该套件附带功能......
  • python类中的@property和@staticmethod分别有什么用,还有其他的吗?
    @property和@staticmethod是Python中常用的装饰器,它们分别有以下特点:@property:@property用于将一个方法转化为属性,从而可以像访问属性一样访问该方法。例如,如果一个类有......