Python数据分析及可视化之Seaborn可视化-实训2

实训:Seaborn库中自带的泰坦尼克数据titanic,进行数据分析与可视化

文章中的素材titanic.csv下载链接

链接:https://pan.baidu.com/s/1_GwUTw7kv2c3ZDjo91sL3A 
提取码:x38v

一、导入模块

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
#用来显示中文标签
plt.rcParams['font.family']=['SimHei']
#用来正常显示正负号
plt.rcParams['axes.unicode_minus'] = False

二、数据获取模块

titanic = pd.read_csv('data/titanic.csv')
print(titanic.head())

三、数据可视化

1、查看有无缺失值

df = titanic.isnull().sum();
print(df)

2、用年龄的均值进行缺失值的填充

mean = titanic['age'].mean()
print('年龄的均值为:',mean)
#将年龄的缺值填充为平均值后,赋给年龄
titanic['age'] = titanic['age'].fillna(mean)
print(titanic.isnull().sum())

3、进行年龄分布的可视化

sns.displot(titanic['age'])
plt.show()

输出结果:

4、显示登船地点的人数

#登船地点的空值有多少
print(titanic['embarked'].isnull().sum())
#将空值填充为S
titanic['embarked'] = titanic['embarked'].fillna('S')
#登船地点的人数的多少
print(titanic['embarked'].value_counts())

输出结果:

5、对于deck字段,由于缺失值太多,将此列删除

del titanic['deck']
print(titanic.head())

6、可视化乘客的性别分析

sns.countplot(x='sex',data=titanic)
plt.show()

输出结果:

7、基于性别,绘制乘客年龄分布箱线图

sns.boxplot(x='sex',y='age',data=titanic)
plt.show()

输出结果:

 

8、对船舱等级进行计数

sns.countplot(x='class',order=['First','Second','Third'],data=titanic)
plt.show()

输出结果:

 

9、结合船舱等级,绘制乘客年龄分布的小提琴图

sns.violinplot(y='age',x='class',data=titanic)
plt.show()

输出结果:

 

10、对年龄进行分级,分成小孩,老人,中年

#定义一个方法,将年龄分级
def agelevel(age):
    if age<=16:
        return 'child'
    elif age>=60:
        return 'old'
    else:
        return 'middle'
#将每个年龄应用方法,生成一个字段'age_level'
titanic['age_level'] = titanic['age'].map(agelevel)
print(titanic.head(8))

输出结果:

 

11、#对分级后的年龄可视化

sns.countplot(x='age_level',data=titanic)
plt.show()

输出结果:

 

12、分析乘客年龄与生还乘客之间的关系

sns.countplot(x='alive',hue='age_level',data=titanic)
plt.legend(loc='best',fontsize='15')
plt.show()

输出结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值