??數(shù)據(jù)分析練習(xí)1,要求:給你1000個(gè)身份證號(hào)碼,告訴我里面有多少男女,各省市人口的分布,這些人的年齡和星座。分析:我要先生成1000個(gè)可以滿足上面分析的身份證,然后進(jìn)行分析,我想最后能夠得到可視化的數(shù)據(jù)。
import random
import datetime
def ident_generator():
#身份證號(hào)的前兩位,省份代號(hào)
province = ('11','12','13','14','15','21','22','23','31','32','33','34','35',
'36','37','41','42','43','44','45','46','50','51','52','53','54','61','62','63','64','65','71','81','82')
#第3-第6位為市和區(qū)的代碼。這里傻瓜式的設(shè)置為隨機(jī)4位數(shù)(我知道這里沒(méi)有0000-0999)
district = random.randint(1000,9999)
#第7-第14位出生的年月日的代碼,這里設(shè)置的是,大于等于18歲左右,小于68歲左右
birthdate = (datetime.date.today() - datetime.timedelta(days = random.randint(6500, 25000)))
#第15-第16位為戶籍所在地派出所。這里傻瓜式的設(shè)置為隨機(jī)2位數(shù)
police_station = random.randint(10,99)
#第17位性別
gender = random.randrange(0,9,1)
#拼接出身份證號(hào)的前17位
ident = province[random.randint(0, 33)] + str(district) + birthdate.strftime("%Y%m%d") + str(police_station) + str(gender)
#將前面的身份證號(hào)碼17位數(shù)分別乘以不同的系數(shù),系數(shù)見coe,然后將這17位數(shù)字和系數(shù)相乘的結(jié)果相加。用加出來(lái)和除以11,看余數(shù)是多少?
coe = {1: 7, 2: 9, 3: 10, 4: 5, 5: 8, 6: 4, 7: 2, 8: 1, 9: 6, 10: 3, 11:7, 12: 9, 13: 10, 14: 5, 15: 8, 16: 4, 17: 2}
summation = 0
#ident[i:i+1]使用的是python的切片獲得每位數(shù)字
for i in range(17):
summation = summation + int(ident[i:i + 1]) * coe[i+1]
#用余數(shù)對(duì)照key得到校驗(yàn)碼,比如余數(shù)為2,則校驗(yàn)碼(第18位)為X
key = {0: '1', 1: '0', 2: 'X', 3: '9', 4: '8', 5: '7', 6: '6', 7: '5', 8: '4', 9: '3', 10: '2'}
check_code = key[summation % 11]
return ident + check_code
def get_constellation(month, date):
dates = (21, 20, 21, 21, 22, 22, 23, 24, 24, 24, 23, 22)
constellations = ("摩羯", "水瓶", "雙魚", "白羊", "金牛", "雙子", "巨蟹", "獅子", "處女", "天秤", "天蝎", "射手", "摩羯")
if date < dates[month-1]:
return constellations[month-1]
else:
return constellations[month]
這里參考的:https://www.cnblogs.com/jiaolong/archive/2011/03/13/1982945.html
他也是參考的人家的,不過(guò)對(duì)12/31的問(wèn)題做了優(yōu)化
ident_generator()
'462467196305067669'
現(xiàn)在,我們有了身份證生成器,我希望,能夠生成1000個(gè)這樣的身份證,然后分析,然后將身份證以及分析得到的數(shù)據(jù)存為CSV文件
import numpy as np
arr = np.empty(shape=(1000,6))
arr.dtype
arr = arr.astype(np.str)
for i in range(1000):
id = ident_generator()
# print (id)
# print (id[0:2])
province_id = {'11':'北京市','12':'天津市','13':'河北省','14':'山西省','15':'內(nèi)蒙古','21':'遼寧省','22':'吉林省',
'23':'黑龍江','31':'上海市','32':'江蘇省','33':'浙江省','34':'安徽省','35':'福建省','36':'江西省',
'37':'山東省','41':'河南省','42':'湖北省','43':'湖南省','44':'廣州省','45':'廣西省','46':'海南省',
'50':'重慶市','51':'四川省','52':'貴州省','53':'云南省','54':'西藏省','61':'陜西省','62':'甘肅省',
'63':'青海省','64':'寧夏省','65':'新疆省','71':'臺(tái)灣省','81':'香港省','82':'澳門省'}
province_out = province_id[id[0:2]]
#print (province_out)
#print (id[6:14])
time = datetime.datetime.strptime(id[6:14], '%Y%m%d').date()
#print (time)
age = 2019 - int(id[6:10]) + 1
#print (age)
gender_id = {'1':'男','2':'女','3':'男','4':'女','5':'男','6':'女','7':'男','8':'女','9':'男','0':'女'}
gender_out = gender_id[id[16]]
#print (gender_out)
month = int(id[10:12])
day = int(id[12:14])
#print (constellation)
# print (get_constellation(month, day))
constellation_out = get_constellation(month, day)
arr[i]=[id,province_out,time,age,gender_out,constellation_out]
import pandas as pd
data_out = pd.DataFrame(arr,columns=('ident','procince','brithday','age','gender','constellation'))
data_out.head()
#data_out.to_csv('../datasets/Id_information.csv')

圖片1
array([['376222196009229908', '山東省', '1960-09-22', '60', '女', '處女'],
['418222197511259677', '河南省', '1975-11-25', '45', '男', '射手'],
['518454195504104083', '四川省', '1955-04-10', '65', '女', '白羊'],
...,
['618246199207136071', '陜西省', '1992-07-13', '28', '男', '巨蟹'],
['211247199809185853', '遼寧省', '1998-09-18', '22', '男', '處女'],
['541181196208276872', '西藏省', '1962-08-27', '58', '男', '處女']],
dtype='<U32')
這里我把這個(gè)存儲(chǔ)為CSV的操作注釋掉了,防止每次運(yùn)行將文件替換掉,那文件里存在的版本為上面這個(gè)。
下面就開始分析。
dataset_url = '../../datasets/Id_information.csv'
data = pd.read_csv(dataset_url)
data.head()
但是我從CSV讀取后,是這樣的:

圖片2
不知道為啥,多了一列索引
data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 7 columns):
Unnamed: 0 1000 non-null int64
ident 1000 non-null object
procince 1000 non-null object
brithday 1000 non-null object
age 1000 non-null int64
gender 1000 non-null object
constellation 1000 non-null object
dtypes: int64(2), object(5)
memory usage: 54.8+ KB
data.describe()

圖片3
data["gender"].value_counts()
女 559
男 441
Name: gender, dtype: int64
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['font.sans-serif']=['SimHei'] #用來(lái)正常顯示中文標(biāo)簽
plt.rcParams['axes.unicode_minus']=False #用來(lái)正常顯示負(fù)號(hào)
plt.figure(figsize=(6,6)) #調(diào)節(jié)圖形大小
labels = [u'女', u'男']
sizes = [559, 441]
colors = 'red', 'orange'
explode = (0.2, 0) # 各類別的偏移半徑
patches,text1,text2 = plt.pie(sizes,
explode=explode,
labels=labels,
colors=colors,
autopct = '%3.2f%%', #數(shù)值保留固定小數(shù)位
shadow = False, #無(wú)陰影設(shè)置
startangle =90, #逆時(shí)針起始角度設(shè)置
pctdistance = 0.6) #數(shù)值距圓心半徑倍數(shù)距離
#patches餅圖的返回值,texts1餅圖外label的文本,texts2餅圖內(nèi)部的文本
plt.axis('equal')
plt.title("男女性別分布情況圖")
plt.legend()
plt.show()

圖片4
data["age"].hist(bins=50, figsize=(8,5))
plt.title("年齡分布情況圖")
plt.xlabel('年齡')
plt.ylabel('人數(shù)')
plt.show()

圖片5