使用seaborn分析泰坦尼克号生还者数据
时间: 2023-11-19 10:04:23 浏览: 149
好的,我们可以使用 Seaborn 可视化库来分析泰坦尼克号的生还者数据。以下是一个基本的示例代码,展示了不同性别、不同船舱等级的生还人数和死亡人数的柱状图:
```python
import seaborn as sns
import pandas as pd
# 读取数据集
titanic = pd.read_csv('titanic.csv')
# 绘制柱状图
sns.countplot(x='Survived', hue='Sex', data=titanic)
sns.catplot(x='Survived', col='Pclass', kind='count', data=titanic)
# 显示图形
sns.plt.show()
```
这段代码会绘制两张柱状图,用来展示不同性别、不同船舱等级的生还人数和死亡人数。第一张图横轴为“Survived”,纵轴为人数,分别展示了男性和女性的生还人数和死亡人数;第二张图横轴为“Survived”,纵轴为人数,分别展示了不同船舱等级的生还人数和死亡人数。您可以根据自己的需求对代码进行修改和调整,来展示您想要的数据和图形。
相关问题
python泰坦尼克号数据集
### 加载和初步探索泰坦尼克号数据集
为了加载并分析泰坦尼克号数据集,在Python环境中可以采用`seaborn`库中的内置函数快速获取该数据集,或者直接读取本地CSV文件。对于前者,仅需一行简单的命令即可完成操作;而后者则适用于那些已经下载好特定版本的数据集的情况。
```python
import seaborn as sns
# 使用Seaborn加载在线提供的泰坦尼克号数据集
titanic = sns.load_dataset("titanic")
print(titanic.head()) # 显示前几条记录以便查看数据结构[^1]
```
当涉及到从本地磁盘加载自定义保存的CSV格式的泰坦尼克号数据集时,则需要用到Pandas库来进行处理:
```python
import pandas as pd
# 假设CSV文件位于当前工作目录下的'train.csv'
train = pd.read_csv('train.csv')
print(train.info()) # 获取有关数据框的信息,包括各列是否存在缺失值等情况[^4]
```
### 数据可视化与基本统计描述
一旦成功加载了所需的数据源之后,下一步就是对其进行一些基础性的探索性数据分析(EDA),这有助于更好地理解变量之间的关系以及可能存在的模式或趋势。这里展示了一个基于年龄层次分组后的生存状态分布情况的例子:
```python
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(8,6))
sns.countplot(x='alive', hue='age_level', data=titanic)
plt.title('Survival Count by Age Level')
plt.show()
```
上述代码片段会绘制一张柱状图,其中x轴代表是否存活(yes/no), 颜色区分不同的年龄段(age_level)[^3]。
### 构建预测模型评估乘客生还可能性
最后一步通常涉及建立机器学习模型来尝试预测哪些因素最能影响一个人能否在这场灾难中幸存下来。下面是一个简单例子展示了如何使用决策树分类器来做这件事,并且通过网格搜索寻找最佳超参数配置以优化性能表现.
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV, train_test_split
X = train.drop(['PassengerId','Survived'], axis=1).fillna(-999)
y = train['Survived']
param_grid = {'max_depth':range(3,20)}
clf = GridSearchCV(estimator=DecisionTreeClassifier(), param_grid=param_grid,cv=5)
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.3,random_state=42)
clf.fit(X_train,y_train)
best_clf = clf.best_estimator_
accuracy_score = best_clf.score(X_test,y_test)
print(f'Best Accuracy Score on Test Set:{accuracy_score:.4f}')
```
这段脚本首先准备好了用于训练的目标向量(`y`) 和 特征矩阵 (`X`), 接着进行了必要的预处理步骤比如填充缺失值[-999], 然后设置了要调整的最大深度范围作为调参空间的一部分; 最终实现了交叉验证过程找到最优参数组合,并报告了在独立测试样本上的准确性得分.
python代码实现泰坦尼克号基础数据可视化处理
以下是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
```
生还者和遇难者的数量柱状图:

男女乘客的数量饼图:

不同等级船舱的乘客数量条形图:

不同年龄段的乘客数量饼图:

阅读全文
相关推荐















