【项目实战】:Python 商铺地址分布数据分析
'''
【項(xiàng)目01】 ?商鋪數(shù)據(jù)加載及存儲(chǔ)
作業(yè)要求:
1、成功讀取“商鋪數(shù)據(jù).csv”文件
2、解析數(shù)據(jù),存成列表字典格式:[{'var1':value1,'var2':value2,'var3':values,...},...,{}]
3、數(shù)據(jù)清洗:
① comment,price兩個(gè)字段清洗成數(shù)字
② 清除字段缺失的數(shù)據(jù)
③ commentlist拆分成三個(gè)字段,并且清洗成數(shù)字
4、結(jié)果存為.pkl文件
?
一 ?文件讀取
①文件讀取:open()
②瀏覽前5 行:readlines()
③ 拆分:split()
f = open('C:/Users/Hjx/Desktop/商鋪數(shù)據(jù).csv','r',encoding='utf8') for i in f.readlines()[:5]:print(i.split(','))二 ?函數(shù)式編程,?并做數(shù)據(jù)清洗
①構(gòu)建函數(shù):def ? ?n(x): ? ? ? ? ? return()
②條件判斷語(yǔ)句:if: ? ?else:
②字符串處理,文字類(lèi)型轉(zhuǎn)化:int(),float()
# 創(chuàng)建comment、price、commentlist清洗函數(shù) # 函數(shù)式編程def fcm(s):if '條' in s:return int(s.split(' ')[0])else:return '缺失數(shù)據(jù)' # comment清洗函數(shù):用空格分段,選取結(jié)果list的第一個(gè)為點(diǎn)評(píng)數(shù),并且轉(zhuǎn)化為整型def fpr(s):if '¥' in s:return float(s.split('¥')[-1])else:return '缺失數(shù)據(jù)' # print清洗函數(shù):用¥分段,選取結(jié)果list的最后一個(gè)為人均價(jià)格,并且轉(zhuǎn)化為浮點(diǎn)型def fcl(s):if ' ' in s:quality = float(s.split(' ')[0][2:])environment = float(s.split(' ')[1][2:])service = float(s.split(' ')[2][2:-1])return [quality,environment,service]else:return '缺失數(shù)據(jù)' # commentlist清洗函數(shù):用空格分段,分別清洗出質(zhì)量、環(huán)境及服務(wù)數(shù)據(jù),并轉(zhuǎn)化為浮點(diǎn)型三 ?數(shù)據(jù)處理
①創(chuàng)建空列表:[ ]
②操縱文件游標(biāo),歸零:seek()
③循環(huán)遍歷,處理數(shù)據(jù):
④ 列表字典化:dict()
⑤裝載數(shù)據(jù):append()
# 數(shù)據(jù)清洗datalst = [] # 創(chuàng)建空列表f.seek(0) n = 0 # 創(chuàng)建計(jì)數(shù)變量 for i in f.readlines()[1:20]:data = i.split(',')#print(data)classify = data[0] # 提取分類(lèi)name = data[1] # 提取店鋪名稱(chēng)comment_count = fcm(data[2]) # 提取評(píng)論數(shù)量star = data[3] # 提取星級(jí)price = fpr(data[4]) # 提取人均add = data[5] # 提取地址qua = fcl(data[6])[0] # 提取質(zhì)量評(píng)分env = fcl(data[6])[1] # 提取環(huán)境評(píng)分ser = fcl(data[6])[2] # 提取服務(wù)評(píng)分if '缺失數(shù)據(jù)' not in [comment_count, price, qua]: # 用于判斷是否有數(shù)據(jù)缺失n += 1data_re = [['classify',classify],['name',name],['comment_count',comment_count],['star',star],['price',price],['address',add],['quality',qua],['environment',env],['service',ser]]datalst.append(dict(data_re)) # 生成字典,并存入列表datalstprint('成功加載%i條數(shù)據(jù)' %n)else:continueprint(datalst) print('總共加載%i條數(shù)據(jù)' %n)四 ?保存文件
永久化文件:pickle
# 數(shù)據(jù)存儲(chǔ).pkl數(shù)據(jù)import pickle pic = open('C:/Users/Hjx/Desktop/data.pkl','wb') pickle.dump(datalst,pic) pic.close() print('finished!') # 將數(shù)據(jù)存成了pkl文件?
總結(jié)
以上是生活随笔為你收集整理的【项目实战】:Python 商铺地址分布数据分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Python】条件及循环语句
- 下一篇: 【Python】对self和_init_