




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
概述:大數(shù)據(jù)可視化【思考與練習(xí)】選擇題(多選)數(shù)據(jù)可視化能用哪種語言實(shí)現(xiàn)?(ABCD)C++語言Java語言Python語言JavaScript語言數(shù)據(jù)可視化可以用哪種符號(hào)元素編碼?(B)長度長度、色彩、尺寸、位置、紋理、方向、形狀以及關(guān)系長度、高度色彩、尺寸、位置、紋理、方向、形狀以及關(guān)系數(shù)據(jù)可視化常用布局有哪些?(D)柱狀圖、餅圖、折線圖表格、散點(diǎn)圖、雷達(dá)圖網(wǎng)絡(luò)圖、時(shí)間線、熱力圖、地圖、樹圖、復(fù)合圖形等以上都對本任務(wù)中測試Python是否安裝成功的語句是?(B)Python-VPython-VPython-RPython-R在使用Python操作MySQL數(shù)據(jù)庫的時(shí)候,創(chuàng)建游標(biāo)時(shí)使用了cursor=pyMySQL.cursors.DictCursor語句,其目的是讓查詢結(jié)果以什么格式輸出?(A)列表嵌套字典列表嵌套元組元組嵌套字典元組嵌套元組在鏈接數(shù)據(jù)庫的字符串中db=pymysql.connect(host="",port=3306,user="root",passwd="123456",db="big_data")中,用戶名是:(C)3306rootbig_data在查詢語句select_sql='SELECT*FROMmap_enword'中,查詢的數(shù)據(jù)表名是:(B)map_enwordrootbig_data實(shí)操練習(xí)題使用for循環(huán),計(jì)算1到100的和。參考答案:sum=0
foriinrange(1,101):
sum+=i
print(sum)#5050使用for循環(huán),計(jì)算10的階乘。參考答案:result=1
foriinrange(2,11):
result*=i
print(result)#3628800查詢四六級(jí)單詞庫中的前十條數(shù)據(jù)。參考答案:importpymysql
"""查詢"""
defselect_db(select_sql):
#建立數(shù)據(jù)庫連接
db=pymysql.connect(
host="",
port=3306,
user="root",
passwd="root",
db="big_data"
)
#通過cursor()創(chuàng)建游標(biāo)對象,并讓查詢結(jié)果以字典格式輸出
cur=db.cursor(cursor=pymysql.cursors.DictCursor)
#使用execute()執(zhí)行sql
cur.execute(select_sql)
#使用fetchall()獲取所有查詢結(jié)果
data=cur.fetchall()
#關(guān)閉游標(biāo)
cur.close()
#關(guān)閉數(shù)據(jù)庫連接
db.close()
returndata
select_sql='SELECT*FROMmap_enwordwhereid<=10'#查詢四六級(jí)單詞庫中的前十條數(shù)據(jù)
words=select_db(select_sql)#將數(shù)據(jù)賦值給變量words
print(words)#查看結(jié)果查詢四六級(jí)單詞庫中以o開頭的單詞數(shù)量。參考答案:importpymysql
"""查詢"""
defselect_db(select_sql):
#建立數(shù)據(jù)庫連接
db=pymysql.connect(
host="",
port=3306,
user="root",
passwd="root",
db="big_data"
)
#通過cursor()創(chuàng)建游標(biāo)對象,并讓查詢結(jié)果以字典格式輸出
cur=db.cursor(cursor=pymysql.cursors.DictCursor)
#使用execute()執(zhí)行sql
cur.execute(select_sql)
#使用fetchall()獲取所有查詢結(jié)果
data=cur.fetchall()
#關(guān)閉游標(biāo)
cur.close()
#關(guān)閉數(shù)據(jù)庫連接
db.close()
returndata
select_sql='SELECTcount(*)FROMmap_enwordwhereenglishlike"o%"'#查詢四六級(jí)單詞庫中以o開頭的單詞數(shù)量
words=select_db(select_sql)#將數(shù)據(jù)賦值給變量words
print(words)#查看結(jié)果項(xiàng)目一:Matplotlib應(yīng)用【思考與練習(xí)】選擇題使用plot()繪制折線圖時(shí)fmt參數(shù)設(shè)置為'rD--',其含義是(A)線段顏色為紅色,菱形點(diǎn)標(biāo)記,破折線連接線段顏色為紅色,菱形點(diǎn)標(biāo)記,實(shí)線連接線段顏色為紅色,窄菱形標(biāo)記,破折線連接線段顏色為紅色,窄菱形標(biāo)記,實(shí)線連接本任務(wù)中使用Matplotlib繪制柱狀圖時(shí),調(diào)用的函數(shù)是(B)plt.plotplt.barplt.barhplt.hist本任務(wù)中調(diào)整y坐標(biāo)軸為對數(shù)軸時(shí),調(diào)用的函數(shù)是(D)plt.ylabelplt.yticksplt.ylimplt.yscale本任務(wù)中使用Matplotlib繪制水平條形圖時(shí),調(diào)用的函數(shù)是(D)A.plt.barB.plt.pieC.plt.histD.plt.barh本任務(wù)中使用Matplotlib繪制詞云圖時(shí),調(diào)用了哪個(gè)庫(B)A.plot_surfaceB.WordCloudC.plt.histD.plt.barh實(shí)操練習(xí)題使用本項(xiàng)目中的四六級(jí)單詞庫數(shù)據(jù)繪制一個(gè)折線圖,要求顏色為綠色,點(diǎn)為5像素大小的實(shí)心圈標(biāo)記,線為2像素粗的點(diǎn)劃線形狀。參考答案:#導(dǎo)入Matplotlib庫
importmatplotlib.pyplotasplt
letter=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
enword=[215,149,528,318,255,245,170,182,274,38,27,175,271,112,148,483,35,396,819,364,110,118,205,1,23,7]
#繪制折線圖
plt.plot(letter,enword,color='green',marker='o',
markersize=5,linestyle='-.',linewidth=2)
#或者
#plt.plot(letter,enword,'go-.',markersize=5,linewidth=2)
plt.show()#展示將本項(xiàng)目任務(wù)1.1.6示例中的圖例位置設(shè)置為為右下角顯示,寫出修改后的完整的示例代碼。參考答案:#導(dǎo)入Matplotlib庫
importmatplotlib.pyplotasplt
letter=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
enword=[215,149,528,318,255,245,170,182,274,38,27,175,271,112,148,483,35,396,819,364,110,118,205,1,23,7]
plt.rcParams['font.sans-serif']=['SimHei']#顯示中文標(biāo)簽
plt.rcParams['axes.unicode_minus']=False#正常顯示負(fù)號(hào)
#繪制條形圖
bar=plt.bar(letter,enword)
plt.legend(handles=bar,labels=['某字母開頭的單詞數(shù)'],loc='lowerright')
#修改坐標(biāo)數(shù)字的字號(hào)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.show()#展示使用下列農(nóng)作物產(chǎn)量數(shù)據(jù),繪制氣泡圖。df_cl={"經(jīng)度":[11,62,86,67,75],"緯度":[71,5,76,112,156],"產(chǎn)量":[41,12,66,32,89]}參考答案:frommatplotlibimportpyplotaspltplt.rcParams['font.sans-serif']=['SimHei']#顯示中文標(biāo)簽
df_cl={"經(jīng)度":[11,62,86,67,75],"緯度":[71,5,76,112,156],"產(chǎn)量":[41,12,66,32,89]}
plt.figure(figsize=(8,6))
plt.scatter(df_cl["經(jīng)度"],df_cl["緯度"],s=df_cl["產(chǎn)量"],alpha=0.6)#增加s氣泡的大小取值,alpha設(shè)置透明度#s設(shè)置點(diǎn)的尺寸,可以是標(biāo)量,也可以是序列,alpha設(shè)置點(diǎn)的透明度
plt.xlabel("經(jīng)度",fontsize=12)#設(shè)置x軸標(biāo)簽
plt.ylabel("維度",fontsize=12)#設(shè)置y軸標(biāo)簽
plt.title("農(nóng)作物分布",fontsize=14)#設(shè)置標(biāo)題
plt.yticks(range(0,91,30))#設(shè)置y軸的刻度
plt.xticks(range(0,181,30))#設(shè)置x軸的刻度
plt.show()使用以下給定數(shù)據(jù)實(shí)現(xiàn)棒棒糖圖。data=[{'letter':'a','num':215},{'letter':'b','num':149},{'letter':'c','num':528},{'letter':'d','num':318},{'letter':'e','num':255},{'letter':'f','num':245},{'letter':'g','num':170},{'letter':'h','num':182},{'letter':'i','num':274},{'letter':'j','num':38},{'letter':'k','num':27},{'letter':'l','num':175},{'letter':'m','num':271},{'letter':'n','num':112},{'letter':'o','num':148},{'letter':'p','num':483},{'letter':'q','num':35},{'letter':'r','num':396},{'letter':'s','num':819},{'letter':'t','num':364},{'letter':'u','num':110},{'letter':'v','num':118},{'letter':'w','num':205},{'letter':'x','num':1},{'letter':'y','num':23},{'letter':'z','num':7}]參考答案:importmatplotlib.pyplotasplt
importnumpyasnp
frompylabimportmpl
#設(shè)置顯示中文字體
mpl.rcParams["font.sans-serif"]=["SimHei"]
data=[{'letter':'a','num':215},{'letter':'b','num':149},{'letter':'c','num':528},{'letter':'d','num':318},{'letter':'e','num':255},{'letter':'f','num':245},{'letter':'g','num':170},{'letter':'h','num':182},{'letter':'i','num':274},{'letter':'j','num':38},{'letter':'k','num':27},{'letter':'l','num':175},{'letter':'m','num':271},{'letter':'n','num':112},{'letter':'o','num':148},{'letter':'p','num':483},{'letter':'q','num':35},{'letter':'r','num':396},{'letter':'s','num':819},{'letter':'t','num':364},{'letter':'u','num':110},{'letter':'v','num':118},{'letter':'w','num':205},{'letter':'x','num':1},{'letter':'y','num':23},{'letter':'z','num':7}]
N=26
x=np.arange(N)
y=[]
foreach_dataindata:
y.append(each_data['num'])
my_label=[]
foreach_dataindata:
my_label.append(each_data['letter'])
fig=plt.figure(figsize=(12,9))
plt.stem(x,y)
plt.ylabel('數(shù)量',fontsize=22)
plt.xticks(ticks=x,labels=my_label,ha='right')
#修改坐標(biāo)數(shù)字的字號(hào)
plt.xticks(fontsize=22)
plt.yticks(fontsize=22)
#自動(dòng)調(diào)整子圖參數(shù),使之填充整個(gè)圖像區(qū)域
plt.tight_layout()
plt.savefig("lollipop_word.png",dpi=300)
plt.show()使用下面的文本數(shù)據(jù)集text繪制詞云圖,要求畫布默認(rèn)長300像素,寬200像素,背景色為黑色。text=“Theworldisbeautiful,butonlythroughhardworkanddiligencecanwecreateabetterlife”參考答案:importmatplotlib.pyplotasplt
fromwordcloudimportWordCloud
#準(zhǔn)備文本數(shù)據(jù)
text=“Theworldisbeautiful,butonlythroughhardworkanddiligencecanwecreateabetterlife”
#創(chuàng)建詞云對象
wordcloud=WordCloud(width=300,height=200,background_color="black").generate(text)
#繪制詞云圖
plt.figure(figsize=(6,6),facecolor=None)
plt.imshow(wordcloud,interpolation="bilinear")
plt.axis("off")
#顯示圖表
plt.show()項(xiàng)目二:Matplotlib實(shí)戰(zhàn)【思考與練習(xí)】選擇題任務(wù)2.1.1向服務(wù)器端發(fā)出HTTP請求,調(diào)用的Python開源包是(C)requestjsonsrequestsjson任務(wù)2.2.2中使用plt.pie函數(shù)繪制餅圖時(shí),對其相關(guān)參數(shù)的描述正確的是以下哪項(xiàng)(A)explode:列表,表示每個(gè)扇區(qū)與圓心的距離,用于突出顯示某些扇區(qū)center:(x,y)元組,表示餅圖的中心位置,默認(rèn)為(1,1)colors:每個(gè)餅塊的顏色。類數(shù)組結(jié)構(gòu)。顏色不可以循環(huán)使用shadow:餅圖下是否有陰影,默認(rèn)值為TureCSV文件格式規(guī)范的特點(diǎn)是(A)數(shù)據(jù)間使用逗號(hào)分隔數(shù)據(jù)間使用分號(hào)分隔數(shù)據(jù)間使用Tab制表符分隔數(shù)據(jù)間使用自定義字符分隔任務(wù)2.2.4中使用plt.bar函數(shù)繪制柱狀圖,對其相關(guān)參數(shù)的描述,不正確的是以下哪項(xiàng)(B)align:表示柱子在x軸上的對齊方式,默認(rèn)為’center’color:柱狀圖的邊框顏色tick_label:柱狀圖的刻度標(biāo)簽linewidth:柱狀圖邊框?qū)挾萂atplotlib工具包的特點(diǎn)不包括以下哪個(gè)選項(xiàng)(B)是一種開源的可視化工具包是一種非開源的可視化工具包能夠繪制散點(diǎn)圖折線圖等基礎(chǔ)圖標(biāo)也能夠繪制熱力圖等一些復(fù)雜圖表實(shí)操練習(xí)題實(shí)現(xiàn)對“豆瓣電影分類排行榜-劇情片”數(shù)據(jù)的抓取。參考答案:importrequestsimportjsonurl='/j/chart/top_list'params={'type':'11','interval_id':'100:90','action':'','start':'0','limit':'200'}headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/101.0.4951.67Safari/537.36'}response=requests.get(url=url,params=params,headers=headers)content=response.json()print(content)withopen('豆瓣電影劇情排行榜.csv','w',encoding='utf-8')asfp:foriincontent:title=i['title']mtype='\\'.join(i['types'])regions='\\'.join(i['regions'])release_date=i['release_date']score=i['score']vote_count=str(i['vote_count'])fp.write(title+','+mtype+','+regions+','+release_date+','+score+','+vote_count+'\n')對“豆瓣電影分類排行榜-劇情片”數(shù)據(jù)進(jìn)行過濾,只輸出豆瓣評分>9.0的排行記錄。參考答案:importrequestsimportjsonurl='/j/chart/top_list'params={'type':'11','interval_id':'100:90','action':'','start':'0','limit':'200'}headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/101.0.4951.67Safari/537.36'}response=requests.get(url=url,params=params,headers=headers)content=response.json()print(content)##foriincontent:##print(json.dumps(i,indent=4,ensure_ascii=False,separators=(',',':')))##breakwithopen('豆瓣電影劇情排行榜.csv','w',encoding='utf-8')asfp:foriincontent:title=i['title']mtype='\\'.join(i['types'])regions='\\'.join(i['regions'])release_date=i['release_date']score=i['score']vote_count=str(i['vote_count'])iffloat(score)>=9.0:fp.write(title+','+mtype+','+regions+','+release_date+','+score+','+vote_count+'\n')對“豆瓣電影分類排行榜-劇情片”數(shù)據(jù)進(jìn)行統(tǒng)計(jì)分析,計(jì)算抓取的記錄條數(shù)和評分的平均值。參考答案:importrequestsimportjsonurl='/j/chart/top_list'params={'type':'11','interval_id':'100:90','action':'','start':'0','limit':'200'}headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/101.0.4951.67Safari/537.36'}response=requests.get(url=url,params=params,headers=headers)content=response.json()print(content)##foriincontent:##print(json.dumps(i,indent=4,ensure_ascii=False,separators=(',',':')))##breakcount=0sum=0.0withopen('豆瓣電影劇情排行榜.csv','w',encoding='utf-8')asfp:foriincontent:title=i['title']mtype='\\'.join(i['types'])regions='\\'.join(i['regions'])release_date=i['release_date']score=i['score']vote_count=str(i['vote_count'])count=count+1sum=sum+float(score)fp.write(title+','+mtype+','+regions+','+release_date+','+score+','+vote_count+'\n')avg=sum/countprint("抓取記錄數(shù)為:"+str(count))print("評分平均值為:"+str(avg))項(xiàng)目三:PyEcharts應(yīng)用【思考與練習(xí)】選擇題(1) (多選)關(guān)于工具箱工具配置項(xiàng)的描述正確的有哪些?(ABCD)A.ToolBoxFeatureSaveAsImageOpts()表示保存圖片B.ToolBoxFeatureDataViewOpts()表示數(shù)據(jù)視圖工具C.ToolBoxFeatureDataZoomOpts()表示數(shù)據(jù)區(qū)域縮放D.ToolBoxFeatureMagicTypeOpts()表示動(dòng)態(tài)類型切換圖例配置項(xiàng)有兩種類型分別是?(A)'plain','scroll''horizontal','vertical''line','bar''True','Fales'下列詞云圖數(shù)據(jù)輸入方式正確的是?(A)[(word1,count1),(word2,count2)][word1,count1,word2,count2](word1,count1),(word2,count2)[{word1,count1},{word2,count2}]象形柱狀圖繪制過程中的symbol_repeat函數(shù)用來指定圖形元素是否重復(fù),該函數(shù)可以取什么值?(A)false/null/undefinedarrowstartorthogonal3D柱狀圖繪制過程中shading函數(shù)控制著三維圖形的著色效果,該函數(shù)可以取到下列何值?(A)realisticleafDepthcenterRadial實(shí)操練習(xí)題1.在本教材任務(wù)3.2.1的基礎(chǔ)上,更換標(biāo)題位置重新輸出圖表。參考答案:c=(
Bar(init_opts=opts.InitOpts())
.add_xaxis(x_data)
.add_yaxis("第一產(chǎn)業(yè)就業(yè)",y_data1)
.add_yaxis("第二產(chǎn)業(yè)就業(yè)",y_data2)
.add_yaxis("第三產(chǎn)業(yè)就業(yè)",y_data3)
.set_global_opts(title_opts=opts.TitleOpts(
title="三次產(chǎn)業(yè)就業(yè)人員數(shù)量",
subtitle='2012年~2021年',
title_textstyle_opts=opts.TextStyleOpts(font_size=22),
pos_right="center"),
legend_opts=opts.LegendOpts(
type_='scroll',
selected_mode='double',
pos_left='center',
pos_top='95%',
orient='horizontal',
)
)
)
c.render_notebook()2.在本教材任務(wù)3.2.1的基礎(chǔ)上,更換標(biāo)題顏色和大小重新輸出圖表。參考答案:c=(
Bar(init_opts=opts.InitOpts())
.add_xaxis(x_data)
.add_yaxis("第一產(chǎn)業(yè)就業(yè)",y_data1)
.add_yaxis("第二產(chǎn)業(yè)就業(yè)",y_data2)
.add_yaxis("第三產(chǎn)業(yè)就業(yè)",y_data3)
.set_global_opts(
title_opts=opts.TitleOpts(
title="2012年~2021年三次產(chǎn)業(yè)就業(yè)人員數(shù)量",
subtitle='近十年',
title_textstyle_opts=opts.TextStyleOpts(color='red',font_size=20),
subtitle_textstyle_opts=opts.TextStyleOpts(color='#f987a2',font_size=20),
pos_right="center"),
legend_opts=opts.LegendOpts(
type_='scroll',
selected_mode='double',
pos_left='center',
pos_top='95%',
orient='horizontal',
)
)
)
print(type(c))
c.render_notebook()3.以數(shù)據(jù)words繪制詞云圖,標(biāo)題設(shè)置為“學(xué)科分類”,words=[("數(shù)學(xué)",230),("語文",124),("英語",436),("物理",255),("化學(xué)",247),("生物",244),("地理",138),("歷史",184),("政治",12),("考研輔導(dǎo)",165),("考研擇校",247)]。參考答案:frompyecharts.chartsimportWordCloud
words=[
("數(shù)學(xué)",230),
("語文",124),
("英語",436),
("物理",255),
("化學(xué)",247),
("生物",244),
("地理",138),
("歷史",184),
("政治",12),
("考研輔導(dǎo)",165),
("考研擇校",247),
]
wc=(
WordCloud()
.set_global_opts(
title_opts=opts.TitleOpts(
title="學(xué)科分類",
pos_right="center",
pos_top="5%",
title_textstyle_opts=opts.TextStyleOpts(color='black',font_size=22),))
.add("",words)
)
wc.render_notebook()項(xiàng)目四:PyEcharts實(shí)戰(zhàn)【思考與練習(xí)】選擇題以下關(guān)于用戶畫像的描述不正確的是哪一項(xiàng)?(B)用戶畫像是指根據(jù)用戶的屬性、用戶偏好、生活習(xí)慣、用戶行為等信息而抽象出來的標(biāo)簽化用戶模型。用戶畫像就不需要給用戶打標(biāo)簽。用戶畫像中的標(biāo)簽是通過對用戶信息分析而來的高度精煉的特征標(biāo)識(shí)。用戶畫像通過打標(biāo)簽可以利用一些高度概括、容易理解的特征來描述用戶(多選)用戶畫像的應(yīng)用場景有哪些?(ABCD)企業(yè)精準(zhǔn)營銷用戶流失用戶偏好產(chǎn)品推薦(多選)屬于用戶畫像標(biāo)簽屬性的是?(ABCD)年齡學(xué)歷婚姻粉絲數(shù)以下哪類圖形可以展示數(shù)據(jù)的區(qū)域位置分布?(D)散點(diǎn)圖柱狀圖折線圖地理圖表(多選)用戶標(biāo)簽主要包括以下哪些?(ABCD)用戶基本特征社會(huì)身份顧客生命周期消費(fèi)偏好實(shí)操練習(xí)題借助DataStat數(shù)據(jù)統(tǒng)計(jì)類,編寫頁面pv/uv統(tǒng)計(jì)函數(shù)page_stat,輸入的rdd包含page、userid、spot_code等列。要求按pv倒序,統(tǒng)計(jì)結(jié)果文件保存/home/ysedu/answer/文件目錄下。參考答案:#頁面pvuv
defpage_stat(rdd):
dim_columns=["page"]
indices=[Count(),CountUniq(["userid"])]
ds=DataStat(dim_columns,indices)
rdd=rdd.filter(lambdar:r["spot_code"]=="spot_interval").map(ds.converts).reduceByKey(ds.calculates).map(ds.map_results)
#根據(jù)pv排序
rdd=rdd.sortBy(lambdar:r[-2],False,1)
#保存
fb=open("/home/ysedu/answer/"+sys._getframe().f_code.co_name,"w")
fb.write('\n'.join(rdd.map(ds.tab_text).collect()))借助DataStat數(shù)據(jù)統(tǒng)計(jì)類和pandas庫,編寫函數(shù)retention_stat計(jì)算用戶訪問的次日留存率~7日留存率,輸入的rdd包含date、userid等列。要求統(tǒng)計(jì)結(jié)果文件保存/home/ysedu/answer/文件目錄下。參考答案:#用戶訪問7日留存率
defretention_stat(rdd):
#首次訪問日期
ds=DataStat(["userid"],[Min(["date"])])
f_rdd=rdd.map(add_date_row).map(ds.converts).reduceByKey(ds.calculates).map(ds.map_results)
#用戶訪問記錄
ds=DataStat(["userid","date"],[])
r_rdd=rdd.map(add_date_row).map(ds.converts).reduceByKey(ds.calculates).map(ds.map_results)
#將rdd轉(zhuǎn)為dataframe
schema=StructType([StructField('userid',StringType()),StructField('first_date',StringType())])
f_df=SQLContext(sc).createDataFrame(f_rdd,schema)
schema=StructType([StructField('userid',StringType()),StructField('request_date',StringType())])
r_df=SQLContext(sc).createDataFrame(r_rdd,schema)
#將兩個(gè)df合并
f_df=f_df.select("*").toPandas()
r_df=r_df.select("*").toPandas()
pd_df=pd.merge(r_df,f_df)#計(jì)算距離首次訪問時(shí)間天數(shù)
pd_df["first_date"]=pd.to_datetime(pd_df["first_date"])
pd_df["request_date"]=pd.to_datetime(pd_df["request_date"])
pd_df['days']=pd_df["request_date"]-pd_df["first_date"]
#創(chuàng)建透視表
data=pd.pivot_table(pd_df,values='userid',index='first_date',columns='days',aggfunc=lambdax:len(x.unique()),fill_value='').reset_index()
#將單元格改為數(shù)值格式,用于后續(xù)計(jì)算留存比例
data=data.applymap(lambdax:pd.to_numeric(x,errors='ignore'))
#留存率計(jì)算,用1days列除以0days為次日留存率,依次類推
create_index=data.columns
pd_df=data.iloc[:,[0,1]]
#這里我們只算到7日留存率
foriinrange(2,8):
s=data[create_index[i]]/data[create_index[1]]
pd_df=pd.concat([pd_df,s],axis=1)
pd_df.columns=['日期','訪問人數(shù)','次日留存率','3日留存率','4日留存率','5日留存率','6日留存率','7日留存率']
pd_df.to_csv("/home/ysedu/answer/"+sys._getframe().f_code.co_name+".csv")根據(jù)stat_result目錄中的total_stat數(shù)據(jù),在jupyter中編寫程序并使用pyecharts柱狀圖展示為總訪問次數(shù)和總訪問人數(shù)兩列。參考答案:#整體pvuv(表格)total_stat
title=["總訪問次數(shù)","總訪問人數(shù)"]
df=pd.read_csv('stat_result/total_stat',sep='\t',header=None
,names=title)
y_data=[int(df.loc[0][0]),int(df.loc[0][1])]
total_stat=(Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
.add_xaxis(title)
.add_yaxis('',y_data)
.set_global_opts(title_opts=opts.TitleOpts(title="整體訪問PV/UV數(shù)據(jù)",subtitle="總訪問次數(shù)/總訪問人數(shù)",pos_left='center'))
)
total_stat.render_notebook()項(xiàng)目五:Plotly應(yīng)用【思考與練習(xí)】選擇題本任務(wù)中使用express繪制柱狀圖時(shí),調(diào)用的函數(shù)是(B)express.Barexpress.barexpress.histogramexpress.Histogram本任務(wù)中使用graph_objs繪制柱狀圖時(shí),調(diào)用的函數(shù)是(A)plotly.graph_objects.Barplotly.graph_objects.barplotly.graph_objects.Histogramplotly.graph_objects.histogram使用express繪制柱狀圖時(shí),barmode參數(shù)設(shè)置為group時(shí),繪制的是?(B)疊加柱狀圖并列柱狀圖覆蓋柱狀圖相對柱狀圖(多選)本任務(wù)中使用graph_objs繪制散點(diǎn)圖時(shí),marker參數(shù)的作用有(ACD)調(diào)整數(shù)據(jù)節(jié)點(diǎn)大小調(diào)整數(shù)據(jù)節(jié)點(diǎn)透明度調(diào)整數(shù)據(jù)節(jié)點(diǎn)顏色調(diào)整數(shù)據(jù)節(jié)點(diǎn)格式(多選)fig.update_layout中的font參數(shù)具有哪些取值?(ABC)colorfamilysizesite要設(shè)置直方圖的透明度,需要控制哪個(gè)參數(shù)?(A)opacitycolor_discrete_sequencecategory_ordersbarmode繪制環(huán)形餅圖時(shí),控制環(huán)形餅圖內(nèi)徑孔的半徑的參數(shù),他的默認(rèn)值為0,取值范圍是多少?(D)0~100~50~200~1以下參數(shù),哪個(gè)是在繪制雙坐標(biāo)軸圖時(shí)用于設(shè)置標(biāo)題格式的?(D)ticktitletickfonttitlefont實(shí)操練習(xí)題1. 使用任務(wù)5.1.2中的數(shù)據(jù),繪制帶文本條柱狀圖。參考答案:importpandasaspd
importnumpyasnp
importplotly.expressaspx
importpymysql
importsqlalchemyassql
importwarnings
warnings.filterwarnings("ignore")
engine=sql.create_engine('mysql+pymysql://root:root@localhost:3306/bdv')
sql1='''select*from1_plastic'''
df=pd.read_sql(sql1,engine)
fig=px.bar(df,
x=df["時(shí)間"],
y=df["農(nóng)用塑料薄膜使用量(噸)"],text_auto=True)
fig.update_layout(font_size=22,legend=dict(
orientation="h",
yanchor="bottom",
y=-0.2,
xanchor="center",
x=0.5,
title_text=''
))
fig.update_xaxes(
side='bottom',
title={'text':''}
)
fig.update_yaxes(
side='left',
title={'text':''}
)
fig.update_layout(
title={
'text':"2012年~2019年農(nóng)用塑料薄膜使用量",
'y':0.95,
'x':0.5
})
fig.show()2. 使用任務(wù)5.1.3中的數(shù)據(jù),繪制圖例在上方的堆疊柱狀圖。參考答案:importplotlyaspy
importplotly.graph_objsasgo
importpandasaspd
importnumpyasnp
importpymysql
importsqlalchemyassql
importwarnings
warnings.filterwarnings("ignore")
engine=sql.create_engine('mysql+pymysql://root:root@localhost:3306/bdv')
sql1='''select*from1_nlmy'''
df=pd.read_sql(sql1,engine)
trace0=go.Bar(x=df["year"],y=df["ny"],name="農(nóng)業(yè)總產(chǎn)值")
trace1=go.Bar(x=df["year"],y=df["ly"],name="林業(yè)總產(chǎn)值")
trace2=go.Bar(x=df["year"],y=df["my"],name="牧業(yè)總產(chǎn)值")
trace3=go.Bar(x=df["year"],y=df["yy"],name="漁業(yè)總產(chǎn)值")
data=[trace0,trace1,trace2,trace3]
layout=go.Layout(title='農(nóng)林牧漁',barmode='stack',font={'size':22})
fig=go.Figure(data=data,layout=layout)
fig.update_layout(font_size=22,legend=dict(
orientation="h",
yanchor="bottom",
y=1.2,
xanchor="center",
x=0.5,
title_text=''
))
fig.update_xaxes(
side='bottom',
title={'text':''}
)
fig.update_yaxes(
side='left',
title={'text':''}
)
fig.update_layout(
title={
'text':"2012年~2021年農(nóng)林牧漁業(yè)總產(chǎn)值",
'y':0.9,
'x':0.5
})
fig.show()3. 使用任務(wù)5.1.4中的數(shù)據(jù),用express繪制并列柱狀圖。參考答案:importplotlyaspy
importplotly.expressaspx
importplotly.graph_objsasgo
importpandasaspd
importnumpyasnp
importpymysql
importsqlalchemyassql
importwarnings
warnings.filterwarnings("ignore")
engine=sql.create_engine('mysql+pymysql://root:root@localhost:3306/bdv')
sql1='''select*from1_fruits'''
df=pd.read_sql(sql1,engine)
trace0=go.Bar(x=df["year"],y=df["gy"],name="果園面積")
trace1=go.Bar(x=df["year"],y=df["xj"],name="香蕉園面積")
trace2=go.Bar(x=df["year"],y=df["pg"],name="蘋果園面積")
trace3=go.Bar(x=df["year"],y=df["gj"],name="柑橘園面積")
trace4=go.Bar(x=df["year"],y=df["ly"],name="梨園面積")
trace5=go.Bar(x=df["year"],y=df["pt"],name="葡萄園面積")
data=[trace0,trace1,trace2,trace3,trace4,trace5]
fig=go.Figure(data)
fig.update_layout(barmode='group')
layout=go.Layout(title='果園面積',barmode='group',font={'size':22})
fig=go.Figure(data=data,layout=layout)
fig.update_layout(font_size=22,legend=dict(
orientation="h",
yanchor="bottom",
y=-0.4,
xanchor="center",
x=0.5,
title_text=''
))
fig.update_xaxes(
side='bottom',
title={'text':''}
)
fig.update_yaxes(
side='left',
title={'text':''}
)
fig.update_layout(
title={
'text':"2012年~2019年果園面積",
'y':0.9,
'x':0.5
})
fig.show()項(xiàng)目六:Plotly實(shí)戰(zhàn)【思考與練習(xí)】選擇題常用的清洗數(shù)據(jù)的包是?(A)PandasMatplotlibSeabornRequest以下哪個(gè)Pandas方法能返回?cái)?shù)據(jù)的行數(shù)和列數(shù)?(A)pd.shapepd.head()pd.tail()pd.drop()以下哪個(gè)Pandas方法能夠刪除缺失數(shù)據(jù)?(B)pd.drop()pd.dropna()pd.delete()pd.loc()Plotly繪制餅圖的方法,需要使用graph_objs中的哪個(gè)函數(shù)?(A)Pie()Scatter()Bar()Histogram()Plotly繪制柱狀圖的方法,需要使用graph_objs中的哪個(gè)函數(shù)?(D)Scatter()Histogram()Pie()Bar()與用戶畫像中無關(guān)的是以下哪個(gè)選項(xiàng)?(D)數(shù)據(jù)清洗和預(yù)處理數(shù)據(jù)可視化數(shù)
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年電梯上行超速制動(dòng)器行業(yè)深度研究分析報(bào)告
- ppp項(xiàng)目補(bǔ)充合同范本
- 中國感應(yīng)干手機(jī)行業(yè)市場深度分析及發(fā)展前景預(yù)測報(bào)告
- 社會(huì)活動(dòng)的視頻記錄構(gòu)圖畫法探討
- 江門溝通拓展訓(xùn)練計(jì)劃
- 生產(chǎn)線調(diào)度的現(xiàn)代化技術(shù)手段探討
- 買魚合同范本
- 證婚婚禮人致辭(匯編15篇)
- 兩山羊訂購合同范本
- 俱樂部投資合同范本
- 新質(zhì)生產(chǎn)力課件
- 傳播學(xué)研究方法
- 1.1公有制為主體 多種所有制經(jīng)濟(jì)共同發(fā)展 課件-高中政治統(tǒng)編版必修二經(jīng)濟(jì)與社會(huì)
- 青春期的婦科知識(shí)講座
- 《社區(qū)康復(fù)》課件-第三章 社區(qū)康復(fù)的實(shí)施
- 中職生心理健康教育全套教學(xué)課件
- JC-T 2704-2022 聚酯纖維裝飾吸聲板
- WTE朗文英語2B 單詞卡片
- 初三物理復(fù)習(xí)計(jì)劃詳細(xì)計(jì)劃
- 汽車懸架概述
- 心房顫動(dòng)的教學(xué)查房課件
評論
0/150
提交評論