
CDA數(shù)據(jù)分析師 出品
作者:CDA教研組
編輯:Mika
背景:以某大型電商平臺的用戶行為數(shù)據(jù)為數(shù)據(jù)集,使用大數(shù)據(jù)處理技術(shù)分析海量數(shù)據(jù)下的用戶行為特征,并通過建立邏輯回歸模型、隨機森林對用戶行為做出預(yù)測;
案例思路:
#全部行輸出
from
IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
數(shù)據(jù)字典:
U_Id:the serialized ID that represents a user
T_Id:the serialized ID that represents an item
C_Id:the serialized ID that represents the category which the corresponding item belongs to Ts:the timestamp of the behavior
Be_type:enum-type from (‘pv’, ‘buy’, ‘cart’, ‘fav’)
pv: Page view of an item's detail page, equivalent to an item click
buy: Purchase an item
cart: Add an item to shopping cart
fav: Favor an item
這里關(guān)鍵是使用dask庫來處理海量數(shù)據(jù),它的大多數(shù)操作的運行速度比常規(guī)pandas等庫快十倍左右。
pandas在分析結(jié)構(gòu)化數(shù)據(jù)方面非常的流行和強大,但是它最大的限制就在于設(shè)計時沒有考慮到可伸縮性。pandas特別適合處理小型結(jié)構(gòu)化數(shù)據(jù),并且經(jīng)過高度優(yōu)化,可以對存儲在內(nèi)存中的數(shù)據(jù)執(zhí)行快速高 效的操作。然而隨著數(shù)據(jù)量的大幅度增加,單機肯定會讀取不下的,通過集群的方式來處理是最好的選 擇。這就是Dask DataFrame API發(fā)揮作用的地方:通過為pandas提供一個包裝器,可以智能的將巨大的DataFrame分隔成更小的片段,并將它們分散到多個worker(幀)中,并存儲在磁盤中而不是RAM中。
Dask DataFrame會被分割成多個部門,每個部分稱之為一個分區(qū),每個分區(qū)都是一個相對較小的 DataFrame,可以分配給任意的worker,并在需要復(fù)制時維護其完整數(shù)據(jù)。具體操作就是對每個分區(qū)并 行或單獨操作(多個機器的話也可以并行),然后再將結(jié)果合并,其實從直觀上也能推出Dask肯定是這么做的。
# 安裝庫(清華鏡像)
# pip install dask -i
https://pypi.tuna.tsinghua.edu.cn/simple
import os
import gc # 垃圾回收接口
from tqdm import tqdm # 進度條庫
import dask # 并行計算接口
from dask.diagnostics import ProgressBar
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import dask.dataframe as dd # dask中的數(shù)表處理庫 import sys # 外部參數(shù)獲取接口
面對海量數(shù)據(jù),跑完一個模塊的代碼就可以加一行g(shù)c.collect()來做內(nèi)存碎片回收,Dask Dataframes與Pandas Dataframes具有相同的API
gc.collect()
42
# 加載數(shù)據(jù)
data = dd.read_csv('UserBehavior_all.csv')# 需要時可以設(shè)置blocksize=參數(shù)來手工指定劃分方法,默認是64MB(需要設(shè)置為總線的倍數(shù),否則會放慢速度)
data.head()
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
data
Dask DataFrame Structure :
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
Dask Name: read-csv, 58 tasks
與pandas不同,這里我們僅獲取數(shù)據(jù)框的結(jié)構(gòu),而不是實際數(shù)據(jù)框。Dask已將數(shù)據(jù)幀分為幾塊加載,這些塊存在 于磁盤上,而不存在于RAM中。如果必須輸出數(shù)據(jù)幀,則首先需要將所有數(shù)據(jù)幀都放入RAM,將它們縫合在一 起,然后展示最終的數(shù)據(jù)幀。使用.compute()強迫它這樣做,否則它不.compute() 。其實dask使用了一種延遲數(shù) 據(jù)加載機制,這種延遲機制類似于python的迭代器組件,只有當(dāng)需要使用數(shù)據(jù)的時候才會去真正加載數(shù)據(jù)。
# 真正加載數(shù)據(jù) data.compute()
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
# 可視化工作進程,58個分區(qū)任務(wù) data.visualize()
數(shù)據(jù)壓縮
# 查看現(xiàn)在的數(shù)據(jù)類型 data.dtypes
U_Id int64
T_Id int64
C_Id int64
Be_type object
Ts int64
dtype: object
# 壓縮成32位uint,無符號整型,因為交易數(shù)據(jù)沒有負數(shù) dtypes = {
'U_Id': 'uint32',
'T_Id': 'uint32',
'C_Id': 'uint32',
'Be_type': 'object',
'Ts': 'int64'
}
data = data.astype(dtypes)
data.dtypes
U_Id uint32
T_Id uint32
C_Id uint32
Be_type object
Ts int64
dtype: object
# 以dask接口讀取的數(shù)據(jù),無法直接用.isnull()等pandas常用函數(shù)篩查缺失值
data.isnull()
Dask DataFrame Structure :
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
columns1 = [ 'U_Id', 'T_Id', 'C_Id', 'Be_type', 'Ts']
tmpDf1 = pd.DataFrame(columns=columns1)
tmpDf1
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
s = data["U_Id"].isna()
s.loc[s == True]
Dask Series Structure:
npartitions=58
bool ...
... ...
...
Name: U_Id, dtype: bool
Dask Name: loc-series, 348 tasks
U_Id列缺失值數(shù)目為0
T_Id列缺失值數(shù)目為0
C_Id列缺失值數(shù)目為0
Be_type列缺失值數(shù)目為0
Ts列缺失值數(shù)目為0
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
無缺失值
數(shù)據(jù)探索與可視化
這里我們使用pyecharts庫。pyecharts是一款將python與百度開源的echarts結(jié)合的數(shù)據(jù)可視化工具。新版的1.X和舊版的0.5.X版本代碼規(guī)則大 不相同,新版詳見官方文檔
https://gallery.pyecharts.org/#/README
# pip install pyecharts -i https://pypi.tuna.tsinghua.edu.cn/simple
Looking in indexes: https:
//pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: pyecharts in d:anacondalibsite-packages (0.1.9.4)
Requirement already satisfied: jinja2 in d:anacondalibsite-packages (from pyecharts)
(3.0.2)
Requirement already satisfied: future in d:anacondalibsite-packages (from pyecharts)
(0.18.2)
Requirement already satisfied: pillow in d:anacondalibsite-packages (from pyecharts)
(8.3.2)
Requirement already satisfied: MarkupSafe>=2.0 in d:anacondalibsite-packages (from
jinja2->pyecharts) (2.0.1)
Note: you may need to restart the kernel to use updated packages.
U_Id列缺失值數(shù)目為0 T_Id列缺失值數(shù)目為0 C_Id列缺失值數(shù)目為0 Be_type列缺失值數(shù)目為0 Ts列缺失值數(shù)目為0
WARNING: Ignoring invalid distribution -umpy (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -ip (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -umpy (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -ip (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -umpy (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -ip (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -umpy (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -ip (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -umpy (d:anacondalibsite-packages)
WARNING: Ignoring invalid distribution -ip (d:anacondalibsite-packages)
# 例如,我們想畫一張漂亮的餅圖來看各種用戶行為的占比 data["Be_type"]
# 使用dask的時候,所有支持的原pandas的函數(shù)后面需加.compute()才能最終執(zhí)行
Be_counts = data["Be_type"].value_counts().compute()
Be_counts
pv 89716264
cart 5530446
fav 2888258
buy 2015839
Name: Be_type, dtype: int64
Be_index = Be_counts.index.tolist() # 提取標(biāo)簽
Be_index
['pv', 'cart', 'fav', 'buy']
Be_values = Be_counts.values.tolist() # 提取數(shù)值
Be_values
[89716264, 5530446, 2888258, 2015839]
from pyecharts import options as opts
from pyecharts.charts import Pie
#pie這個包里的數(shù)據(jù)必須傳入由元組組成的列表
c = Pie()
c.add("", [list(z) for z in zip(Be_index, Be_values)]) # zip函數(shù)的作用是將可迭代對象打包成一 個個元組,然后返回這些元組組成的列表 c.set_global_opts(title_opts=opts.TitleOpts(title="用戶行為")) # 全局參數(shù)(圖命名) c.set_series_opts(label_opts=opts.LabelOpts(formatter=": {c}"))
c.render_notebook() # 輸出到當(dāng)前notebook環(huán)境
# c.render("pie_base.html") # 若需要可以將圖輸出到本機
<pyecharts.charts.basic_charts.pie.Pie at 0x1b2da75ae48>
<div id="490361952ca944fcab93351482e4b254" style="width:900px; height:500px;"></div>
from pyecharts.charts import Funnel # 舊版的pyecharts不需要.charts即可import import pyecharts.options as opts
from IPython.display import Image as IMG
from pyecharts import options as opts
from pyecharts.charts import Pie
<pyecharts.charts.basic_charts.funnel.Funnel at 0x1b2939d50c8>
<div id="071b3b906c27405aaf6bc7a686e36aaa" style="width:800px; height:400px;"></div>
時間戳轉(zhuǎn)換
dask對于時間戳的支持非常不友好
type(data)
dask.dataframe.core.DataFrame
data['Ts1']=data['Ts'].apply(lambda x: time.strftime("%Y-%m-%d %H:%M:%S",
time.localtime(x)))
data['Ts2']=data['Ts'].apply(lambda x: time.strftime("%Y-%m-%d", time.localtime(x)))
data['Ts3']=data['Ts'].apply(lambda x: time.strftime("%H:%M:%S", time.localtime(x)))
D:anacondalibsite-packagesdaskdataframecore.py:3701: UserWarning:
You did not provide metadata, so Dask is running your function on a small dataset to
guess output types. It is possible that Dask will guess incorrectly.
To provide an explicit output types or to silence this message, please provide the
`meta=` keyword, as described in the map or apply function that you are using.
Before: .apply(func)
After: .apply(func, meta=('Ts', 'object'))
warnings.warn(meta_warning(meta))
data.head(1)
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
data.dtypes
U_Id uint32
T_Id uint32
C_Id uint32
Be_type object
Ts int64
Ts1 object
Ts2 object
Ts3 object
dtype: object
抽取一部分數(shù)據(jù)來調(diào)試代碼
df = data.head(1000000)
df.head(1)
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
用戶流量和購買時間情況分析
用戶行為統(tǒng)計表
describe = df.loc[:,["U_Id","Be_type"]]
ids = pd.DataFrame(np.zeros(len(set(list(df["U_Id"])))),index=set(list(df["U_Id"])))
pv_class=describe[describe["Be_type"]=="pv"].groupby("U_Id").count()
pv_class.columns = ["pv"]
buy_class=describe[describe["Be_type"]=="buy"
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認 ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預(yù)測分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢預(yù)判? ? 在數(shù)據(jù)驅(qū)動決策的時代,預(yù)測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經(jīng)濟蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學(xué)方法在市場調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學(xué)方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03