Python數(shù)據(jù)分析實(shí)戰(zhàn)之分布分析

◆?◆?◆ ?◆?◆
import pandas as pdimport matplotlib.pyplot as pltimport math
>>> df = pd.read_csv('UserInfo.csv')>>> df.info()RangeIndex: 1000000 entries, 0 to 999999Data columns (total 4 columns):UserId 1000000 non-null int64CardId 1000000 non-null int64LoginTime 1000000 non-null objectDeviceType 1000000 non-null objectdtypes: int64(2), object(2)memory?usage:?30.5+?MB
#?提取出生日期需要先把身份證號(hào)碼轉(zhuǎn)換成字符串>?df['CardId']?=?df['CardId'].astype('str')#?提取出生日期,并生成新字段> df['DateofBirth'] = df.CardId.apply(lambda x : x[6:10]+"-"+x[10:12]+"-"+x[12:14])#?提取性別,待觀察性別分布> df['Gender'] = df['CardId'].map(lambda x : 'Male' if int(x[-2]) % 2 else 'Female')> df.head()

3.計(jì)算年齡
#?提取出生日期:月和日>>> df[['month','day']] = df['DateofBirth'].str.split('-',expand=True).loc[:,1:2]# 提取小月,查看是否有31號(hào)>>> df_small_month = df[df['month'].isin(['02','04','06','09','11'])]#?無(wú)效數(shù)據(jù),如圖所示>>> df_small_month[df_small_month['day']=='31']# 統(tǒng)統(tǒng)刪除,均為無(wú)效數(shù)據(jù)>>> df.drop(df_small_month[df_small_month['day']=='31'].index,inplace=True)#?同理,校驗(yàn)2月>>> df_2 = df[df['month']=='02']#?2月份的校驗(yàn)大家可以做的仔細(xì)點(diǎn)兒,先判斷是否潤(rùn)年再進(jìn)行刪減>>> df_2[df_2['day'].isin(['29','30','31'])]# 統(tǒng)統(tǒng)刪除>>> df.drop(df_2[df_2['day'].isin(['29','30','31'])].index,inplace=True)

# 計(jì)算年齡# 方法一df['Age'] = df['DateofBirth'].apply(lambda x : math.floor((pd.datetime.now() - pd.to_datetime(x)).days/365))# 方法二df['DateofBirth'].apply(lambda x : pd.datetime.now().year - pd.to_datetime(x).year)
# 查看年齡區(qū)間,進(jìn)行分區(qū)>>> df['Age'].max(),df['Age'].min()# (45, 18)>>> bins = [0,18,25,30,35,40,100]>>> labels = ['18歲及以下','19歲到25歲','26歲到30歲','31歲到35歲','36歲到40歲','41歲及以上']>>> df['年齡分層'] = pd.cut(df['Age'],bins, labels = labels)
#?查看是否有重復(fù)值>>> df.duplicated('UserId').sum()????#47681#?數(shù)據(jù)總條目>>> df.count() #980954

>>> df.groupby('年齡分層')['UserId'].count()年齡分層18歲及以下 2526219歲到25歲 25450226歲到30歲 18175131歲到35歲 18141736歲到40歲 18158941歲及以上 156433Name:?UserId,?dtype:?int64#?通過(guò)求和,可知重復(fù)數(shù)據(jù)也被計(jì)算進(jìn)去>>> df.groupby('年齡分層')['UserId'].count().sum()# 980954>>> df.groupby('年齡分層')['UserId'].nunique()年齡分層18歲及以下 2401419歲到25歲 24219926歲到30歲 17283231歲到35歲 17260836歲到40歲 17280441歲及以上 148816Name:?UserId,?dtype:?int64>>> df.groupby('年齡分層')['UserId'].nunique().sum()#?933273??=?980954(總)-47681(重復(fù))#?計(jì)算年齡分布>>> result = df.groupby('年齡分層')['UserId'].nunique()/df.groupby('年齡分層')['UserId'].nunique().sum()>>> result# 結(jié)果年齡分層18歲及以下 0.02573119歲到25歲 0.25951626歲到30歲 0.18518931歲到35歲 0.18494936歲到40歲 0.18515941歲及以上 0.159456Name:?UserId,?dtype:?float64#?格式化一下>>> result = round(result,4)*100>>> result.map("{:.2f}%".format)年齡分層18歲及以下 2.57%19歲到25歲 25.95%26歲到30歲 18.52%31歲到35歲 18.49%36歲到40歲 18.52%41歲及以上 15.95%Name:?UserId,?dtype:?object


回復(fù):微信 獲取
記得點(diǎn)在看~我是嚴(yán)小樣兒

評(píng)論
圖片
表情
