python数据分析和可视化【5】泰坦尼克号幸存者数据分析

使用Seaborn库中的函数,对泰坦尼克号幸存者数据“titanic”进行数据分析与可视化。
要求:
1)查看有无缺失值。
2)用年龄的均值进行缺失值的填充。
3)利用Seaborn绘制年龄的直方图和密度图。
4)显示登船地点(S,C,Q)的人数。
5)用柱状图可视化乘客的性别分布。
6)基于性别,绘制乘客年龄分布箱线图。
7)对年龄进行分级,分开老人和小孩的数据。
数据集:
在这里插入图片描述
代码实现:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

# 读取泰坦尼克号数据集
titanic = pd.read_csv('C:\\Users\86178\Desktop\seaborn-data\\titanic.csv')

# 1. 查看是否有缺失值
print(titanic.isnull().sum())

# 2. 用年龄的均值填充缺失值
titanic['age'].fillna(titanic['age'].mean(), inplace=True)

# 3. 绘制年龄的直方图和密度图
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
sns.histplot(titanic['age'], kde=False, bins=20, color='skyblue')
plt.title('Age Histogram')

plt.subplot(1, 2, 2)
sns.kdeplot(titanic['age'], color='orange', shade=True)
plt.title('Age Density Plot')

plt.show()

# 4. 显示登船地点(S,C,Q)的人数
print(titanic['embark_town'].value_counts())

# 5. 用柱状图可视化乘客的性别分布
plt.figure(figsize=(6, 4))
sns.countplot(x='sex', data=titanic, palette='Set1')
plt.title('Passenger Gender Distribution')
plt.show()

# 6. 基于性别,绘制乘客年龄分布箱线图
plt.figure(figsize=(6, 4))
sns.boxplot(x='sex', y='age', data=titanic, palette='Set2')
plt.title('Age Distribution by Gender')
plt.show()

# 7. 对年龄进行分级,分开老人和小孩的数据
titanic['Age_group'] = pd.cut(titanic['age'], bins=[0, 12, 60, 100], labels=['Child', 'Adult', 'Elderly'])
print(titanic['Age_group'].value_counts())

运行结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT牛爷爷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值