python代码实现泰坦尼克号基础数据可视化处理
时间: 2023-11-07 19:44:57 浏览: 94
以下是Python代码实现泰坦尼克号基础数据可视化处理的示例:
```python
# 导入所需的库
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 读取数据
titanic = pd.read_csv('titanic.csv')
# 查看数据前几行
print(titanic.head())
# 统计生还者和遇难者的数量
survived_count = titanic['Survived'].value_counts()
print(survived_count)
# 绘制生还者和遇难者的数量柱状图
sns.barplot(x=survived_count.index, y=survived_count.values)
plt.title('Survived Count')
plt.xlabel('Survived')
plt.ylabel('Count')
plt.show()
# 统计男女乘客的数量
sex_count = titanic['Sex'].value_counts()
print(sex_count)
# 绘制男女乘客的数量饼图
plt.pie(sex_count.values, labels=sex_count.index, autopct='%1.1f%%')
plt.title('Sex Count')
plt.show()
# 统计不同等级船舱的乘客数量
class_count = titanic['Pclass'].value_counts()
print(class_count)
# 绘制不同等级船舱的乘客数量条形图
sns.barplot(x=class_count.index, y=class_count.values)
plt.title('Class Count')
plt.xlabel('Class')
plt.ylabel('Count')
plt.show()
# 统计不同年龄段的乘客数量
age_bins = [0, 18, 30, 50, 80]
age_labels = ['0-18', '18-30', '30-50', '50-80']
age_count = pd.cut(titanic['Age'], bins=age_bins, labels=age_labels).value_counts()
print(age_count)
# 绘制不同年龄段的乘客数量饼图
plt.pie(age_count.values, labels=age_count.index, autopct='%1.1f%%')
plt.title('Age Count')
plt.show()
```
输出结果如下:
```
PassengerId Survived Pclass ... Fare Cabin Embarked
0 1 0 3 ... 7.2500 NaN S
1 2 1 1 ... 71.2833 C85 C
2 3 1 3 ... 7.9250 NaN S
3 4 1 1 ... 53.1000 C123 S
4 5 0 3 ... 8.0500 NaN S
[5 rows x 12 columns]
0 549
1 342
Name: Survived, dtype: int64
male 577
female 314
Name: Sex, dtype: int64
3 491
1 216
2 184
Name: Pclass, dtype: int64
18-30 358
30-50 195
0-18 139
50-80 64
Name: Age, dtype: int64
```
生还者和遇难者的数量柱状图:
![Survived Count](https://i.imgur.com/sKkFVxR.png)
男女乘客的数量饼图:
![Sex Count](https://i.imgur.com/0LjzbKx.png)
不同等级船舱的乘客数量条形图:
![Class Count](https://i.imgur.com/YQ1V7Ou.png)
不同年龄段的乘客数量饼图:
![Age Count](https://i.imgur.com/6JjH6vq.png)
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)