python 描述性分析_python数据分析:美国巴尔的摩16年公务员工资数据集描述性分析...

小咪咪 2023-01-01 05:54 226阅读 0赞

一、项目背景

本次练习使用的数据集为美国城市巴尔的摩2016年公务员工资的数据集,将通过数据可视化和数据描述性分析等手段,分析其工资分布情况。

二、数据来源

其中,一共有13818条数据,7个字段,分别为:

Name(姓名)

JobTitle(职位名称)

AgencyID(工号)

Agency(单位)

HireDate(入职日期)

AnnualSalary(年薪)

GrossPay(总薪资-税前)

三、定义问题

本次练习将围绕工资数据集进行。分别会以下问题展现分析:

- 年薪的总体分布情况

- 年薪最高的职务,人数最多的职位

- 公务人员入职日期的情况

四、数据清洗与整理

# 设置notebook cell多行输出

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = ‘all’ #默认为’last’

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import os

import warnings

os.chdir(r’E:\python_learn\train’) # 设置相对路径

warnings.filterwarnings(‘ignore’) # 设置忽略警告

plt.style.use(‘ggplot’) # 设置matplotlib的整体风格

file_name = ‘Baltimore_City_Employee_Salaries_FY2016.csv’

salary = pd.read_csv(file_name)

salary.head()

![Image 1][]

返回数据前5条.png

# 查看数据结构

salary.info()

RangeIndex: 13818 entries, 0 to 13817

Data columns (total 7 columns):

Name 13818 non-null object

JobTitle 13818 non-null object

AgencyID 13818 non-null object

Agency 13818 non-null object

HireDate 13818 non-null object

AnnualSalary 13818 non-null object

GrossPay 13546 non-null object

dtypes: object(7)

memory usage: 755.8+ KB

从返回的数据信息和结构信息可知,HireDate、AnnualSalary和GrossPay这3个字段的数据类型与实际不符,AnnualSalary和GrossPay字段的数据含有特殊符号,并且GrossPay字段部分数据缺失。

因此接下来要对存在问题的字段进行以下的清洗和整理工作:

GrossPay字段的缺失数据处理

AnnualSalary和GrossPay字段删除特殊符号

AnnualSalary和GrossPay str → numeric

HireDate str → datetime

JobTitle、Agency str → category

# 缺失值判断及处理

salary.isna().sum()

salary.isna().sum().sum()

# 缺失数据比例较少,可以选择删除处理

Name 0

JobTitle 0

AgencyID 0

Agency 0

HireDate 0

AnnualSalary 0

GrossPay 272

dtype: int64

272

salary = salary.dropna()

salary.isna().sum()

salary.isna().sum().sum() # 缺失数据处理完成

Name 0

JobTitle 0

AgencyID 0

Agency 0

HireDate 0

AnnualSalary 0

GrossPay 0

dtype: int64

0

# AnnualSalary和GrossPay字段删除特殊符号

def f(x):

return x.strip(‘$’) # 删除$符号

salary[‘AnnualSalary’] = salary[‘AnnualSalary’].map(f)

salary[‘GrossPay’] = salary[‘GrossPay’].map(f)

salary.head()

![Image 1][]

返回数据前5条.png

# HireDate、AnnualSalary和GrossPay这3个字段转换为与实际数据相符的数据类型

# AnnualSalary和GrossPay → float

salary[‘AnnualSalary’] = salary[‘AnnualSalary’].astype(float)

salary[‘GrossPay’] = salary[‘GrossPay’].astype(float)

# HireDate → datetime

salary[‘HireDate’] = pd.to_datetime(salary[‘HireDate’])

salary.head()

salary.info() # 查看转换后的数据结构 → 数据清洗后一共13546条数据

![Image 1][]

返回数据前5条和数据结构.png

# 异常值检测

salary_num = salary.iloc[:,5:]

# 箱型图检测

color = dict(boxes=’DarkGreen’, whiskers=’DarkOrange’, medians=’DarkBlue’, caps=’Gray’) # 颜色设置

box = salary_num.plot.box(figsize=(10,6),color=color)

plt.title(‘Outliers detection box chart’,fontsize=14,pad=12)

# 筛出异常值

lst = []

cols = salary_num.columns

for col in cols:

salary_num_col = salary_num[col]

q1 = salary_num_col.quantile(0.25)

q3 = salary_num_col.quantile(0.75)

iqr = q3-q1

ma = q3+iqr*1.5

mi = q1-iqr*1.5

err = salary_num_col[(salary_num_col > ma) | (salary_num_col < mi)]

lst.append(err)

err_data = pd.concat(lst)

print(‘一共检测出异常数据%i条!’%(len(err_data)),’\n’)

print(‘异常数据展示前10条 \n’,err_data.head(10))

Text(0.5, 1.0, ‘Outliers detection box chart’)

一共检测出异常数据343条!

异常数据展示前10条

306 132600.0

448 130100.0

803 127500.0

849 132200.0

1183 130200.0

1336 138200.0

1352 157100.0

1658 127500.0

1938 166320.0

2193 129587.0

dtype: float64

![Image 1][]

箱型图检测异常.png

鉴于不清楚异常值的产生原因,以及对美国公务人员的工资制度等信息不清楚,暂不对异常数据进行处理。

五、数据探索

5.1总体情况

# 人数

number_salary = salary[‘AgencyID’].count()

print(‘数据集涵盖的样本数为:%i’%number_salary)

数据集涵盖的样本数为:13546

# 单位

def s(x):

return x.split(‘(‘)[0]

salary[‘Agency’] = salary[‘Agency’].map(s) # 按左括号分裂

salary[‘Agency’] = salary[‘Agency’].astype(‘category’)

company_count = len(salary[‘Agency’].cat.categories)

print(‘数据集涵盖的单位数为:%i个’%company_count)

数据集涵盖的单位数为:67个

# 职位

salary[‘JobTitle’] = salary[‘JobTitle’].astype(‘category’) # 将JobTitle转为分类数据

post_count = len(salary[‘JobTitle’].cat.categories)

print(‘数据集涵盖的职位数为:%i个’%post_count)

数据集涵盖的职位数为:1034个

# 人均年薪

per_salary = salary[‘AnnualSalary’].sum()/number_salary

print(‘美国城市巴尔的摩2016年公务员人均年薪为:%.2f 美元’%per_salary)

美国城市巴尔的摩2016年公务员人均年薪为:53507.98 美元

5.2工资总体分布情况

年薪总体分布

最高年薪

年薪最多人数的区间

# 工资总体分布情况 —->>> 直方图描述

salary[‘AnnualSalary’].hist(figsize=(8,6),bins=20,alpha=0.8)

plt.title(‘AnnualSalary’,pad=12)

plt.xlabel(‘AnnualSalary’,fontsize=12,labelpad=10)

plt.ylabel(‘Number of people’,fontsize=12,labelpad=10)

![Image 1][]

直方图.png

1、从直方图的分布反映出,年薪的总体分布基本呈正态分布,但分布向左倾斜,说明美国城市巴尔的摩公务员高工资的职位还是较少。

2、其中,年薪在4-8万美元之间的公务员占大部分,最高年薪达15万美元。

5.3工资与职位的分布情况

年薪最高的职位

人数最多的职位

# 职位工资分布

post_salary = salary.groupby(‘JobTitle’).mean()[‘AnnualSalary’].sort_values(ascending=False).head(10)

post_salary # 平均年薪排名前10的职位

JobTitle

STATE’S ATTORNEY 238772.0

Police Commissioner 200000.0

Executive Director V 182500.0

MAYOR 171635.0

Executive Director III 171306.5

CITY SOLICITOR 169800.0

DIRECTOR PUBLIC WORKS 169800.0

CITY AUDITOR 163000.0

Deputy Police Commissioner 154900.0

Executive Director I 153905.0

Name: AnnualSalary, dtype: float64

# 柱状图描述

post_salary.plot(kind=’bar’,

colormap=’Blues_r’,

alpha=0.8,

width=0.8,

figsize=(12,6),

rot=45,

)

plt.ylim([0,300000])

plt.title(‘Top 10 positions with average annual salary - picture01’,fontsize=14,pad=12)

plt.ylabel(‘Average annual salary’,fontsize=12,labelpad=12)

for x,y in zip(range(len(post_salary)),post_salary):

plt.text(x,y+0.5,’%.f’%y,ha=’center’,va=’bottom’,fontsize=12,)

![Image 1][]

图1.png

# 职位人数分布

post_people = salary.groupby(‘JobTitle’).count()[‘AgencyID’].sort_values(ascending=False).head(10)

post_people # 人数最多的前10职位

JobTitle

POLICE OFFICER 1756

LABORER (Hourly) 551

EMT Firefighter Suppression 351

RECREATION ARTS INSTRUCTOR 319

OFFICE SUPPORT SPECIALIST III 303

CROSSING GUARD 260

POLICE OFFICER (EID) 251

COMMUNITY AIDE 245

POLICE SERGEANT 235

SEASONAL MAINT AIDE 207

Name: AgencyID, dtype: int64

# 柱状图描述

post_people.plot(kind=’bar’,

colormap=’Greens_r’,

alpha=0.8,

width=0.8,

figsize=(12,6),

rot=45,

)

plt.ylim([0,2000])

plt.title(‘Top 10 positions with the largest number of people - Picture02’,fontsize=14,pad=12)

for x,y in zip(range(len(post_people)),post_people):

plt.text(x,y,’%.f’%y,ha=’center’,va=’bottom’,fontsize=12,)

![Image 1][]

图2.png

1、如柱状图1所示,年薪最高的职位为STATE’S ATTORNEY(州检察官),其次为Police Commissioner(警察局长)和Executive Director V(执行董事)

2、如柱状图2所示,人数最多的职位为POLICE OFFICER(警务人员),其次为LABORER-Hourly(小时劳工)和EMT Firefighter Suppression(消防员)

5.4公务员入职情况

公务人员2016年入职分布情况,入职人数最多的月份

# 公务人员2016年入职分布情况

salary[‘month’] = salary[‘HireDate’].dt.month # 添加一列月份列

salary.head()

entry_month = salary.groupby(‘month’).count()[‘AgencyID’]

entry_month

![Image 1][]

返回结果.png

# 柱状图描述

entry_month.plot(kind=’barh’,

figsize=(14,8),

colormap=’Oranges_r’,

alpha=0.8,

width=0.7,

)

plt.title(‘Employment distribution of public servants in 2016’,fontsize=14,pad=12)

plt.xlim([0,1800])

plt.xlabel(‘Number_of_people’,labelpad=12)

for x,y in zip(entry_month,range(len(entry_month))):

plt.text(x,y,’%.f’%x,ha=’left’,va=’center’,fontsize=12,)

![Image 1][]

入职分布-条形图.png

# 折线图

entry_month.plot(kind=’line’,

figsize=(10,6),

colormap=’Blues_r’,

alpha=0.8,

)

plt.ylabel(‘Number of people’,labelpad=12)

plt.title(‘Employment distribution of public servants in 2016’,fontsize=14,pad=12)

plt.xlim([1,12])

plt.ylim([0,1800])

plt.axhline(y=entry_month.mean(),ls=’—‘,c=’r’,lw=0.8,alpha=0.5,) #添加人数均值水平直线

plt.text(x=6,y=entry_month.max()+30,s=entry_month.max(),fontdict={‘size’:14,’color’:’r’})

plt.text(x=12+0.1,y=entry_month.mean(),s=round(entry_month.mean()),fontdict={‘size’:14,’color’:’r’})

![Image 1][]

入职分布-折线图.png

1、入职人数在月均入职人数1129人附近上下波动。

2、入职人数最多为6月份,共入职1468人,而入职人数最少为2月,其次为4月。

六、总结

1、从数据集所涵盖数据中,样本数量为13546,涵盖67个单位,1034个职位的数据,样本类别分布是否均衡未知。

2、美国巴尔的摩2016年公务员人均年薪为53507.98美元,其公务员高工资的职位较少,公务员年薪普遍集中在4-8万美元之间,最高年薪达到15万美元。

3、其中年薪最高的TOP3职位分别为州检察官,警察局长和执行董事;而人数最多TOP3职位则分别为警务人员,小时劳工和EMT消防员。

4、其入职人数最多为6月份,入职人数最少为2月和4月。

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,226人围观)

还没有评论,来说两句吧...

相关阅读

    相关 4.2 数据描述性统计

    定义:反映在一定时间、空间条件下某种现象的总体规模、总水平或总成果的统计指标。eg:营业额、利润等2、定义:两个有相互联系的指标数值之比eg:目标完成率(实际完成/计划完...

    相关 python数据分析-相关分析

    python数据分析-相关分析 概念 在现实中,事物与事物之间或多或少存在一定的关系,数据之间也不例外,数据与数据之间关系往往提醒安于互相依存的关系,而相关分