數(shù)據(jù)蛙-Python進(jìn)階

這是漫長(zhǎng)的一周,本周完成了Python的進(jìn)階模塊,主要是pandas、numpy、matplotlib、seaborn、pyecharts這些模塊的學(xué)習(xí)以及一個(gè)實(shí)際的案例:商品銷售情況分析,之前一直覺得課程難度不夠,但到這一周難度就大大提高了。尤其是案例練習(xí)中的RFM模型和用戶生命周期建立,看懂不難但是自己寫一直出錯(cuò),在不斷出錯(cuò)不斷嘗試中知識(shí)得到了積累,另外可視化部分沒有什么練習(xí)題,希望后面可以加上一些這方面的練習(xí),接下來(lái)分模塊來(lái)總結(jié)一下學(xué)習(xí)的內(nèi)容。

本周完成情況

Pandas:

重新設(shè)置索引:df.set_index()

Series格式轉(zhuǎn)換為DataFrame:df.to_frame()

文件讀?。簆d.read_csv(filepath, header = 0,skiprows=[1,2])?

pandas 的索引? ??

使用位置做索引:df.loc[0]????????使用列表做索引:df.loc[[0,1,2]]

使用切片做索引:df.loc[0:4]????????使用bool類型索引:df[df['年齡']>30]

iloc 和 loc 的區(qū)別

loc 是基于索引值的,切片是左閉右閉的

iloc 是基于位置的,切片是左閉右開的

修改列索引:df.rename(columns={'姓名':'name', '年齡':'age'},inplace=True)

替換一個(gè)值:df.replace({'name':{'小明':'xiaoming'}},inplace=True)

對(duì)數(shù)據(jù)進(jìn)行排序:df.sort_values('age')

累加求和:df.cumsum(0)

刪除列:del df['player']?????????刪除行:df.drop(labels=0)?labels 是行列的名字

數(shù)據(jù)拼接:pd.concat([left,right],axis=1)

數(shù)據(jù)關(guān)聯(lián):

# 指定列進(jìn)行關(guān)聯(lián),默認(rèn)是 inner join ????result = pd.merge(left,right,on='key')

#多個(gè)關(guān)聯(lián)條件:result = pd.merge(left, right, on=['key1', 'key2'])

#左連接:result = pd.merge(left, right, how='left', on=['key1', 'key2'])

# 列名不一樣的關(guān)聯(lián):pd.merge(left,right,left_on = ['key1','key2'],right_on = ['key3','key4'])

分組操作:

#單個(gè)分組:groups = df.groupby('district')

# 作用多個(gè)聚合函數(shù):groups.agg([np.mean,np.sum,np.std])

# 針對(duì)具體列聚合 groups.age.agg([np.mean,np.sum,np.std])

# 不同列不同聚合函數(shù) groups.agg({"age":np.mean,"novip_buy_times":np.sum})

分組后該列值求和顯示:groups['vip_buy_times'].transform('sum')

通常用于求占比:transform(lambda x: x /sum(x))

numpy

# 填充指定值:np.full([3,4],1)

# 起始為10,5為步長(zhǎng),30為結(jié)尾取不到:np.arange(10, 30, 5)

#隨機(jī)矩陣:np.random.random((2,3))

# 平均劃分:np.linspace( 0, 2*pi, 100 )

# 類型及轉(zhuǎn)換:vector.astype('float')

# 多維變一維:matrix.ravel()

# 矩陣的擴(kuò)展:a = np.arange(0, 40, 10)? ? b = np.tile(a, (3, 5))? ? # 行變成3倍,列變成5倍

# 水平拼接:np.hstack((a,b))? 豎直拼接:np.vstack((a,b))

# 豎直分割:np.hsplit(a,3)? ? #水平分割:np.vsplit(a,3)

pandas100道練習(xí)題

8. Select the data in rows [3, 4, 8] and in columns ['animal', 'age'].

A:df.loc[df.index[[3,4,8]],['animal','age']]

行采用位置,列采用普通索引,這里利用index函數(shù)將位置變化為具體的普通索引,再利用loc函數(shù)

19. The 'priority' column contains the values 'yes' and 'no'. Replace this column with a column of boolean values: 'yes' should be True and 'no' should be False

A1:df['priority'].replace(['yes','no'],[True,False],inplace=True) 用replace函數(shù)替換

A2:df['priority'] = df['priority'].map({'yes': True, 'no': False}) 用map函數(shù)替換

最大最小值的索引:df.idxmax、df.idxmin

找出最大最小的前N個(gè)數(shù):nlargest()和nsmallest()?

將原表分組 并設(shè)置分段區(qū)間 pd.cut(df['A'], np.arange(0, 101, 10))

resample函數(shù) 日期重采樣:s.resample('M').mean()

TimeGrouper 重組:s.groupby(pd.TimeGrouper('4M')).idxmax()

split 分割函數(shù):temp = df['From_To'].str.split('_', expand=True) True為DataFrame

兩個(gè)DataFrame拼接用join:df = df.join(temp)

matplotlib

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei'] #用來(lái)正常顯示中文標(biāo)簽

plt.rcParams['axes.unicode_minus']=False #用來(lái)正常顯示負(fù)號(hào)

%matplotlib inline 直接顯示

折線圖:plt.plot(x,y,color = 'r')

柱狀圖:plt.bar(x,y)? plt.barh(x,y) 多個(gè)bar x設(shè)置不同 堆積圖 bottom設(shè)置不同

散點(diǎn)圖:plt.scatter(x, y, c=colors, alpha=0.5, s = area)

直方圖:plt.hist(a,bins= 20) bin代表分隔的最小單位

plt.legend() 顯示圖例

for a,b in zip(X+W[i],data[i]):

? ? plt.text(a,b,"%.0f"% b,ha="center",va= "bottom") 添加數(shù)據(jù)標(biāo)簽

plt.annotate('注釋文本',xy=(1, np.sin(1)),xytext=(2, 0.5), fontsize=16,arrowprops=dict(arrowstyle="->")) 添加注釋文本

plt.xlabel("Group") x軸標(biāo)題

plt.ylabel("Num") y軸標(biāo)題

fig, axes = plt.subplots(nrows=2, ncols=2,facecolor='darkslategray')? 繪制多個(gè)圖形

axes[0,0] axes[0,1] axes[1,0] axes[1,1]

pylab.rcParams['figure.figsize'] = (10, 6) # 調(diào)整圖片大小

pyecharts

動(dòng)態(tài)展示圖表

from pyecharts.charts import Bar

from pyecharts import options as opts

** pyecharts 繪圖的五個(gè)步驟:**

創(chuàng)建圖形對(duì)象:bar = Bar()

添加繪圖數(shù)據(jù):bar.add_xaxis(["襯衫", "毛衣", "領(lǐng)帶", "褲子", "風(fēng)衣", "高跟鞋", "襪子"])

? ? ? ? ???????????????? bar.add_yaxis("商家A", [114, 55, 27, 101, 125, 27, 105])

? ? ? ? ? ? ? ? ? ? ? ? ?bar.add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49])

配置系列參數(shù):對(duì)標(biāo)簽、線型等的一些設(shè)置

配置全局參數(shù):bar.set_global_opts(title_opts=opts.TitleOpts(title="銷售情況"))

渲染圖片:生成本地 HTML 文件 bar.render("mycharts.html")? bar.render()

notebook 渲染:bar.render_notebook()

鏈?zhǔn)秸{(diào)用(推薦)

bar = (Bar()

? ? .add_xaxis(["襯衫", "毛衣", "領(lǐng)帶", "褲子", "風(fēng)衣", "高跟鞋", "襪子"])

? ? .add_yaxis("商家A", [114, 55, 27, 101, 125, 27, 105])

? ? .add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49])

? ? .set_global_opts(title_opts=opts.TitleOpts(title="某商場(chǎng)銷售情況"))

)

bar.render_notebook()

柱狀圖:Bar()

條形圖:bar.reversal_axis() #翻轉(zhuǎn)XY軸,將柱狀圖轉(zhuǎn)換為條形圖

折線圖:from pyecharts.charts import Line? line=Line()

餅圖:from pyecharts.charts import Page, Pie????Pie()?

數(shù)據(jù)可視化項(xiàng)目

日期處理

轉(zhuǎn)換日期類型:df['order_dt']=pd.to_datetime(df.order_dt,format="%Y%m%d")

將日期轉(zhuǎn)換為月為單位:df['month']=df.order_dt.values.astype('datetime64[M]')所有日期顯示為當(dāng)月第一天

去除日期單元值:order_diff/np.timedelta64(1,'D')


過(guò)濾部分極值:grouped_user.sum().query('order_products<100').order_amount

數(shù)據(jù)透視表:rfm=df.pivot_table(index='user_id',values=['order_products','order_amount'],aggfunc={'order_amount':'sum','order_products':'sum'})


map() 方法是pandas.series.map()方法, 對(duì)DF中的元素級(jí)別的操作, 可以對(duì)df的某列或某多列

applymap(func) 也是DF的屬性, 對(duì)整個(gè)DF所有元素應(yīng)用func操作

purchase_r=pivoted_counts.applymap(lambda x: 1 if x>1 else np.NaN if x==0 else 0)

apply(func) 是DF的屬性, 對(duì)DF中的行數(shù)據(jù)或列數(shù)據(jù)應(yīng)用func操作,也可用于Series

apply(lambda x:x.cumsum()/x.sum())? ? 累計(jì)占比

apply(lambda x:x/x.sum(),axis=0)? ? ?每一列中每行數(shù)據(jù)占比


下周開始進(jìn)入數(shù)據(jù)分析思維的課程,很期待后面的課程以及項(xiàng)目,加油!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容