【Python基礎】Python數(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
#?提取出生日期需要先把身份證號碼轉換成字符串>?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.計算年齡
#?提取出生日期:月和日>>> df[['month','day']] = df['DateofBirth'].str.split('-',expand=True).loc[:,1:2]# 提取小月,查看是否有31號>>> df_small_month = df[df['month'].isin(['02','04','06','09','11'])]#?無效數(shù)據,如圖所示>>> df_small_month[df_small_month['day']=='31']# 統(tǒng)統(tǒng)刪除,均為無效數(shù)據>>> df.drop(df_small_month[df_small_month['day']=='31'].index,inplace=True)#?同理,校驗2月>>> df_2 = df[df['month']=='02']#?2月份的校驗大家可以做的仔細點兒,先判斷是否潤年再進行刪減>>> 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)

# 計算年齡# 方法一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ū)間,進行分區(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)
#?查看是否有重復值>>> df.duplicated('UserId').sum()????#47681#?數(shù)據總條目>>> df.count() #980954

>>> df.groupby('年齡分層')['UserId'].count()年齡分層18歲及以下 2526219歲到25歲 25450226歲到30歲 18175131歲到35歲 18141736歲到40歲 18158941歲及以上 156433Name:?UserId,?dtype:?int64#?通過求和,可知重復數(shù)據也被計算進去>>> 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(重復)#?計算年齡分布>>> result = df.groupby('年齡分層')['UserId'].nunique()/df.groupby('年齡分層')['UserId'].nunique().sum()>>> result# 結果年齡分層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

往期精彩回顧
獲取一折本站知識星球優(yōu)惠券,復制鏈接直接打開:
https://t.zsxq.com/662nyZF
本站qq群1003271085。
加入微信群請掃碼進群(如果是博士或者準備讀博士請說明):
評論
圖片
表情
