Pandas数据分析练习7

练习7-可视化

探索泰坦尼克灾难数据


步骤1 导入必要的库

运行以下代码

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

import numpy as np

%matplotlib inline

步骤2 从以下地址导入数据

运行以下代码

# 本地对应的"train.csv"路径

path7 = 'D:/hailong/hailong_download/pandas_exercise/exercise_data/train.csv'   

步骤3 将数据框命名为titanic

运行以下代码

titanic = pd.read_csv(path7)

titanic.head()

输出结果

步骤4 将PassengerId设置为索引

运行以下代码

titanic.set_index('PassengerId').head()

输出结果

步骤5 绘制一个展示男女乘客比例的扇形图

运行以下代码

# sum the instances of males and females

males = (titanic['Sex'] == 'male').sum()

females = (titanic['Sex'] == 'female').sum()

# put them into a list called proportions

proportions = [males,females]

# Create a pie chart

plt.pie(

    # using proportions

    proportions,

    # with the labels being officer names

    labels = ['Males','Females'],

    # with no shadows

    shadow = False,

    # with colors

    colors = ['blue','red'],

    # with one slide exploded out

    explode = (0.15,0),

    # with the start angle at 90%

    startangle = 90,

    # with the percent listed as a fraction

    autopct = '%1.1f%%'

)

# View the plot drop above

plt.axis('equal')

# Set labels

plt.title("Sex Proportion")

# View the plot

plt.tight_layout()

plt.show()

输出结果

注意撸代码的时候尽量不要写错

步骤6 绘制一个展示船票Fare, 与乘客年龄和性别的散点图

运行以下代码

# creates the plot using

lm = sns.lmplot(x = 'Age', y = 'Fare', data = titanic, hue = 'Sex', fit_reg = False)

# set title

lm.set(title = 'Fare x Age')

# get the axes object and tweak it

axes = lm.axes

axes[0,0].set_ylim(-5,)

axes[0,0].set_ylim(-5,85)

输出结果

步骤7 有多少人生还?

运行以下代码

titanic.Survived.sum()

输出结果:342

步骤8 绘制一个展示船票价格的直方图

运行以下代码

# sort the values from the top to the least value and slice the first 5 items

df = titanic.Fare.sort_values(ascending = False)

df

# create bins interval using numpy

binsVal = np.arange(0,600,10)

binsVal

# create the plot

plt.hist(df,bins = binsVal)

# Set the title and labels

plt.xlabel('Fare')

plt.ylabel('Frequency')

plt.title('Fare Payed Histrogram')

# show the plot

plt.show()

输出结果

代码截图

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容