DataWhale第三次任务 数据重构

数据的合并

任务一:将data文件夹里面的所有数据都载入,与之前的原始数据相比,观察他们的之间的关系

import numpy as np
import pandas as pd
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")
text_left_up.head()

在这里插入图片描述

任务二:使用concat方法:将数据train-left-up.csv和trainright-up.csv横向合并为一张表,并保存这张表为result_up

result_up  = pd.concat([text_left_up,text_right_up ], axis= 1,join='inner' ) #内连接取交集片

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

result_down = pd.concat([text_left_down, text_right_down], axis = 1, join = 'inner' ) 
result=pd.concat([result_up,result_down],join='outer',axis=0)#外连接取并集   outer, 表示index全部需要; inner,表示只取index重合的部分
result.head()

在这里插入图片描述

任务四:使用DataFrame自带的方法join方法和append:完成任务二和任务三的任务

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()

任务五:使用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()

在这里插入图片描述

换一种角度看数据

任务一:将我们的数据变为Series类型的数据

result.to_csv('result.csv', index = False)
text = pd.read_csv('result.csv')
text.head()
unit_result = text.stack().head(20)
unit_result.head

在这里插入图片描述
stack 和unstack 用法

数据聚合与运算

任务一:通过教材《Python for Data Analysis》P303、Google or anything来学习了解GroupBy机制

groupby用法

任务二:计算泰坦尼克号男性与女性的平均票价

df = text['Fare'].groupby(text['Sex'])
df
for name, group in df:
    print(name)
    print(group)
means = df.mean()
means

在这里插入图片描述

任务三:统计泰坦尼克号中男女的存活人数

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

在这里插入图片描述

任务四:计算客舱不同等级的存活人数

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

在这里插入图片描述

任务五:统计在不同等级的票中的不同年龄的船票花费的平均值

dd = text.groupby(['Pclass', 'Age'])['Fare'].mean().head()

在这里插入图片描述

任务六:将任务二和任务三的数据合并,并保存到sex_fare_survived.csv

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

在这里插入图片描述

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

survived_age = text['Survived'].groupby(text['Age']).sum()
#各年龄段存活人数
text.groupby('Age').count()['Embarked']
#各年龄段总人数
text.groupby(['Age']).sum()['Survived']/text.groupby('Age').count()['Embarked']
#各年龄段存活率
survived_age[text.groupby(['Age'['Survived'].sum().values==max(text.groupby(['Age'])['Survived'].sum())]
#存活人数最多的年龄段
max(text.groupby(['Age']['Survived'].sum())/sum(text.groupby(['Age'])['Survived'].sum())
#本写法不对因为age列存在nan,groupby结果中会默认删除nan的数据

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48626051/article/details/108190747