AI時代技能Python數(shù)據(jù)分析與可視化實戰(zhàn)教程_第1頁
AI時代技能Python數(shù)據(jù)分析與可視化實戰(zhàn)教程_第2頁
AI時代技能Python數(shù)據(jù)分析與可視化實戰(zhàn)教程_第3頁
AI時代技能Python數(shù)據(jù)分析與可視化實戰(zhàn)教程_第4頁
AI時代技能Python數(shù)據(jù)分析與可視化實戰(zhàn)教程_第5頁
已閱讀5頁,還剩15頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

AI時代技能:Python數(shù)據(jù)分析與可視化實戰(zhàn)教程Python作為現(xiàn)代編程語言中的佼佼者,在數(shù)據(jù)分析與可視化領(lǐng)域展現(xiàn)出強大的能力。隨著人工智能時代的到來,掌握Python數(shù)據(jù)分析與可視化技能已成為眾多行業(yè)從業(yè)者的必備能力。本文將深入探討Python在數(shù)據(jù)分析與可視化方面的實戰(zhàn)應(yīng)用,涵蓋數(shù)據(jù)獲取、清洗、分析及可視化等關(guān)鍵環(huán)節(jié),通過具體案例展示Python如何賦能數(shù)據(jù)驅(qū)動決策。一、Python數(shù)據(jù)分析環(huán)境搭建進行數(shù)據(jù)分析前,需要搭建合適的開發(fā)環(huán)境。Python自帶的解釋器可以滿足基本需求,但專業(yè)的數(shù)據(jù)分析工作需要更完善的環(huán)境配置。推薦使用Anaconda發(fā)行版,它集成了Python解釋器、JupyterNotebook、Pandas、NumPy、Matplotlib等核心數(shù)據(jù)分析庫,并提供conda包管理工具。安裝Anaconda后,可以通過以下命令創(chuàng)建虛擬環(huán)境,確保項目間的依賴管理:pythoncondacreate-ndata_analyticspython=3.8pandasnumpymatplotlibseaborncondaactivatedata_analyticsJupyterNotebook是數(shù)據(jù)分析的理想工具,其交互式界面便于代碼編寫、結(jié)果展示和文檔記錄。啟動Notebook后,可以創(chuàng)建新的筆記本或使用內(nèi)置的魔法命令簡化代碼執(zhí)行:python生成隨機數(shù)并繪制直方圖%matplotlibinlineimportnumpyasnpimportmatplotlib.pyplotaspltdata=np.random.normal(0,1,1000)plt.hist(data,bins=30)plt.title('隨機正態(tài)分布')plt.xlabel('值')plt.ylabel('頻率')plt.show()二、數(shù)據(jù)獲取與處理數(shù)據(jù)分析的第一步是獲取數(shù)據(jù)。Python提供了多種數(shù)據(jù)獲取方式,包括API調(diào)用、網(wǎng)絡(luò)爬蟲和文件讀取等。2.1從API獲取數(shù)據(jù)現(xiàn)代許多服務(wù)提供RESTfulAPI供數(shù)據(jù)獲取。使用requests庫可以方便地調(diào)用API:pythonimportrequestsurl="/data"headers={"Authorization":"Beareryour_token"}response=requests.get(url,headers=headers)data=response.json()將JSON數(shù)據(jù)轉(zhuǎn)換為PandasDataFrameimportpandasaspddf=pd.DataFrame(data["results"])2.2網(wǎng)絡(luò)爬蟲對于沒有提供API的數(shù)據(jù)源,可以使用BeautifulSoup和Scrapy等庫進行網(wǎng)頁爬?。簆ythonimportrequestsfrombs4importBeautifulSoupurl="/table"response=requests.get(url)soup=BeautifulSoup(response.text,"html.parser")table=soup.find("table")rows=table.find_all("tr")data=[]forrowinrows:cols=row.find_all("td")cols=[col.text.strip()forcolincols]data.append(cols)df=pd.DataFrame(data[1:],columns=data[0])2.3數(shù)據(jù)清洗獲取的數(shù)據(jù)往往需要清洗才能使用。Pandas提供了強大的數(shù)據(jù)清洗功能:python檢查缺失值print(df.isnull().sum())刪除缺失值df_cleaned=df.dropna()填充缺失值df_filled=df.fillna(0)數(shù)據(jù)類型轉(zhuǎn)換df["date"]=pd.to_datetime(df["date"])去重df_unique=df.drop_duplicates()窗口函數(shù)df["moving_avg"]=df["value"].rolling(window=7).mean()三、探索性數(shù)據(jù)分析探索性數(shù)據(jù)分析(EDA)是理解數(shù)據(jù)特征的關(guān)鍵步驟。Pandas和Matplotlib提供了豐富的可視化工具。3.1描述性統(tǒng)計python基本統(tǒng)計描述print(df.describe())分位數(shù)分析print(df["value"].quantile([0.25,0.5,0.75]))相關(guān)性分析correlation=df.corr()print(correlation)繪制相關(guān)性熱力圖importseabornassnsplt.figure(figsize=(10,8))sns.heatmap(correlation,annot=True,cmap="coolwarm")plt.title("相關(guān)性熱力圖")plt.show()3.2數(shù)據(jù)可視化3.2.1單變量分析python直方圖plt.figure(figsize=(10,6))sns.histplot(df["value"],kde=True)plt.title("值分布直方圖")plt.xlabel("值")plt.ylabel("頻率")plt.show()箱線圖plt.figure(figsize=(10,6))sns.boxplot(x=df["category"],y=df["value"])plt.title("按類別分的值箱線圖")plt.xlabel("類別")plt.ylabel("值")plt.show()3.2.2多變量分析python散點圖矩陣sns.pairplot(df[["value1","value2","value3"]])plt.suptitle("散點圖矩陣",y=1.02)plt.show()條形圖plt.figure(figsize=(12,8))sns.barplot(x="category",y="value",hue="sub_category",data=df)plt.title("按類別和子類別的值條形圖")plt.xlabel("類別")plt.ylabel("值")plt.xticks(rotation=45)plt.show()3.3時空分析python時間序列圖df["date"]=pd.to_datetime(df["date"])df.set_index("date",inplace=True)plt.figure(figsize=(12,6))df["value"].resample("M").mean().plot()plt.title("月度平均值時間序列")plt.xlabel("日期")plt.ylabel("平均值")plt.show()地理數(shù)據(jù)可視化importgeopandasasgpdimportmatplotlib.pyplotaspltgdf=gpd.read_file("path/to/geojson")gdf["value"]=df["value"]fig,ax=plt.subplots(1,1,figsize=(10,8))gdf.plot(column="value",ax=ax,legend=True,legend_kwds={"label":"值分布","orientation":"horizontal"})plt.title("地理分布熱力圖")plt.show()四、高級數(shù)據(jù)分析技術(shù)4.1機器學(xué)習(xí)應(yīng)用pythonfromsklearn.model_selectionimporttrain_test_splitfromsklearn.linear_modelimportLinearRegressionfromsklearn.metricsimportmean_squared_error,r2_score準(zhǔn)備數(shù)據(jù)X=df[["feature1","feature2"]]y=df["target"]劃分訓(xùn)練集和測試集X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)訓(xùn)練模型model=LinearRegression()model.fit(X_train,y_train)評估模型y_pred=model.predict(X_test)mse=mean_squared_error(y_test,y_pred)r2=r2_score(y_test,y_pred)print(f"均方誤差:{mse}")print(f"決定系數(shù):{r2}")特征重要性coefficients=pd.DataFrame({"feature":X.columns,"importance":model.coef_})coefficients.sort_values("importance",ascending=False,inplace=True)print(coefficients)4.2交互式可視化使用Plotly和Bokeh可以創(chuàng)建交互式可視化,便于探索和分析:pythonimportplotly.expressaspx創(chuàng)建交互式散點圖fig=px.scatter(df,x="feature1",y="feature2",color="category",size="value",hover_data=["target"],title="交互式散點圖")fig.update_layout(width=800,height=600)fig.show()創(chuàng)建交互式儀表盤importdashfromdashimportdcc,html,Input,Outputapp=dash.Dash(__name__)app.layout=html.Div([dcc.Graph(id='interactive-plot'),dcc.Slider(id='year-slider',min=df['date'].dt.year.min(),max=df['date'].dt.year.max(),value=df['date'].dt.year.min(),marks={str(year):str(year)foryearindf['date'].dt.year.unique()},step=1)])@app.callback(Output('interactive-plot','figure'),[Input('year-slider','value')])defupdate_plot(selected_year):filtered_df=df[df['date'].dt.year==selected_year]fig=px.scatter(filtered_df,x="feature1",y="feature2",color="category",size="value",hover_data=["target"])returnfigif__name__=='__main__':app.run_server(debug=True)五、實戰(zhàn)案例:電商銷售數(shù)據(jù)分析5.1案例背景某電商平臺需要分析過去一年的銷售數(shù)據(jù),以優(yōu)化產(chǎn)品策略和營銷活動。數(shù)據(jù)包含訂單信息、用戶信息、產(chǎn)品信息和促銷活動記錄。5.2數(shù)據(jù)準(zhǔn)備python讀取數(shù)據(jù)orders=pd.read_csv("orders.csv")products=pd.read_csv("products.csv")customers=pd.read_csv("customers.csv")promotions=pd.read_csv("promotions.csv")數(shù)據(jù)合并sales_data=orders.merge(products,on="product_id")sales_data=sales_data.merge(customers,on="customer_id")sales_data=sales_data.merge(promotions,on="promotion_id",how="left")日期處理sales_data["order_date"]=pd.to_datetime(sales_data["order_date"])sales_data["year"]=sales_data["order_date"].dt.yearsales_data["month"]=sales_data["order_date"].dt.monthsales_data["day"]=sales_data["order_date"].dt.day5.3分析與可視化5.3.1銷售趨勢分析python月度銷售趨勢monthly_sales=sales_data.groupby([sales_data["order_date"].dt.to_period("M")])["revenue"].sum()plt.figure(figsize=(12,6))monthly_sales.plot()plt.title("月度銷售趨勢")plt.xlabel("月份")plt.ylabel("銷售額")plt.show()日銷售波動daily_sales=sales_data.groupby([sales_data["order_date"].dt.to_period("D")])["revenue"].sum()plt.figure(figsize=(12,6))daily_sales.plot()plt.title("日銷售波動")plt.xlabel("日期")plt.ylabel("銷售額")plt.show()5.3.2產(chǎn)品分析python熱銷產(chǎn)品top_products=sales_data.groupby("product_name")["quantity"].sum().sort_values(ascending=False).head(10)plt.figure(figsize=(12,6))sns.barplot(x=top_products.values,y=top_products.index)plt.title("熱銷產(chǎn)品")plt.xlabel("銷售量")plt.ylabel("產(chǎn)品名稱")plt.show()產(chǎn)品類別分析product_category_sales=sales_data.groupby("category")["revenue"].sum().sort_values(ascending=False)plt.figure(figsize=(10,6))product_category_sales.plot(kind="pie",autopct="%1.1f%%")plt.title("按類別的銷售額分布")plt.ylabel("")plt.show()5.3.3用戶分析python用戶地域分布customer_region=sales_data.groupby("region")["customer_id"].nunique().sort_values(ascending=False)plt.figure(figsize=(10,6))sns.barplot(x=customer_region.index,y=customer_region.values)plt.title("用戶地域分布")plt.xlabel("地區(qū)")plt.ylabel("用戶數(shù)量")plt.xticks(rotation=45)plt.show()用戶購買頻率customer_frequency=sales_data.groupby("customer_id").size().value_counts(normalize=True).sort_index()plt.figure(figsize=(10,6))customer_frequency.plot()plt.title("用戶購買頻率分布")plt.xlabel("購買次數(shù)")plt.ylabel("用戶比例")plt.show()5.3.4促銷活動效果python促銷活動效果promotion_effect=sales_data.groupby("promotion_name")["revenue"].sum().sort_values(ascending=False)plt.figure(figsize=(12,6))sns.barplot(x=p

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論