2021-07-17

数据重构

准备工作

(1)导入基本库`

import numpy as np
import pandas as pd

(2)载入文件result.csv

text = pd.read_csv('result.csv')
text.head()

2数据的合并

(1)将文件train-left-up.csv,train-left-down.csv,train-right-up.csv,train-right-down.csv里面的所有数据都载入,与之前的原始数据相比,观察他们的之间的关系

text_left_up = pd.read_csv("train-left-up.csv")
text_left_down = pd.read_csv("train-left-down.csv")
text_right_up = pd.read_csv("train-right-up.csv")
text_right_down = pd.read_csv("train-right-down.csv")

结果

image.png

image.png

(2)使用concat方法:将数据train-left-up.csv和train-right-up.csv横向合并为一张表,并保存这张表为result_up

list_up = [text_left_up,text_right_up]
result_up = pd.concat(list_up,axis=1)
result_up.head()

结果

image.png

(3)使用concat方法:将train-left-down和train-right-down横向合并为一张表,并保存这张表为result_down。然后将上边的result_up和result_down纵向合并为result

list_down=[text_left_down,text_right_down]
result_down = pd.concat(list_down,axis=1)
result = pd.concat([result_up,result_down])
result.head()
image.png

(4)使用DataFrame自带的方法join方法和append:完成(2)和(3)

resul_up = text_left_up.join(text_right_up)
result_down = text_left_down.join(text_right_down)
result = result_up.append(result_down)
result.head()
image.png

(5)使用Panads的merge方法和DataFrame的append方法

result_up = pd.merge(text_left_up,text_right_up,left_index=True,right_index=True)
result_down = pd.merge(text_left_down,text_right_down,left_index=True,right_index=True)
result = resul_up.append(result_down)
result.head()

结果

image.png

(6)完成的数据保存为result.csv

result.to_csv('result.csv')

3换一种角度看数据

(1)将我们的数据变为Series类型的数据

# 将完整的数据加载出来
text = pd.read_csv('result.csv')
text.head()
# 代码写在这里
unit_result=text.stack().head(20)
unit_result.head()
image.png

(2)将代码保存为unit_result,csv

unit_result.to_csv('unit_result.csv')

(3)加载数据

test = pd.read_csv('unit_result.csv')
test.head()

结果

image.png

4. 数据运用

(1)计算泰坦尼克号男性与女性的平均票价

df  = text['Fare'].groupby(text['Sex'])
means = df.mean()
means

结果

image.png

(2)统计泰坦尼克号中男女的存活人数

survived_sex = text['Survived'].groupby(text['Sex']).sum()
survived_sex.head()

结果

image.png

(3)计算客舱不同等级的存活人数

survived_pclass = text['Survived'].groupby(text['Pclass'])
survived_pclass.sum()
image.png

(4)从(2)到(3)中,这些运算可以通过agg()函数来同时计算。并且可以使用rename函数修改列名

text.groupby('Sex').agg({'Fare': 'mean', 'Pclass': 'count'}).rename(columns=
                            {'Fare': 'mean_fare', 'Pclass': 'count_pclass'})
image.png

(5)统计在不同等级的票中的不同年龄的船票花费的平均值

image.png

(6)将(2)和(3)数据合并,并保存到sex_fare_survived.csv

result = pd.merge(means,survived_sex,on='Sex')
resul
image.png
result.to_csv('sex_fare_survived.csv')

(7)得出不同年龄的总的存活人数,然后找出存活人数的最高的年龄,最后计算存活人数最高的存活率(存活人数/总人数)

#不同年龄的存活人数
survived_age = text['Survived'].groupby(text['Age']).sum()
survived_age.head()
#找出最大值的年龄段
survived_age[survived_age.values==survived_age.max()]
#首先计算总人数
_sum = text['Survived'].sum()

print("sum of person:"+str(_sum))

precetn =survived_age.max()/_sum

print("最大存活率:"+str(precetn))
image.png

你可能感兴趣的:(2021-07-17)