准备工作
复习:在前面我们已经学习了
Pandas
基础,第二章我们开始进入数据分析的业务部分,在第二章第一节的内容中,我们学习了数据的清洗,这一部分十分重要,只有数据变得相对干净,我们之后对数据的分析才可以更有力。而这一节,我们要做的是数据重构,数据重构依旧属于数据理解(准备)的范围开始之前,导入numpy、pandas包和数据
# 导入基本库 import numpy as np import pandas as pd
载入data文件中的:train-left-up.csv
#绝对路径 df = pd.read_csv("C:\\Users\\86171\\Desktop\\datawhale\\hands-on-data-analysis-master\\第二章项目集合\\data\\train-left-up.csv")
#相对路径 df2=pd.read_csv("data/train-left-up.csv")
注意路径的格式
l_u = pd.read_csv("data/train-left-up.csv")
l_d = pd.read_csv("data/train-left-down.csv")
r_u = pd.read_csv("data/train-right-up.csv")
r_d = pd.read_csv("data/train-right-down.csv")
l_u.head()
查看导入结果
PassengerId | Survived | Pclass | Name | |
---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) |
4 | 5 | 0 | 3 | Allen, Mr. William Henry |
其他的三个同样查看导入的结果可以发现,这几个
DataFrame
就是train.csv
的一部分,把他们拼接之后就是完整的train.csv
concat
方法:将数据train-left-up.csv和train-right-up.csv横向合并为一张表,并保存这张表为result_upresult_up=pd.concat([l_u,r_u],axis=1)#横向
concat
方法:将train-left-down和train-right-down横向合并为一张表,并保存这张表为result_down。然后将上边的result_up和result_down纵向合并为result。关于axis为0/1的区别
#横向合并参数为1
result_down=pd.concat([l_d,r_d],axis=1)
#纵向合并参数为0
result =pd.concat([result_up,result_down],axis=0)
验证合并结果
print(result.shape)
(891, 12)
DataFrame
自带的方法join
方法和append
:完成任务二和任务三的任务查看官方文档:
看出
join
就是把列横向合并
append
就是将行纵向合并
join
和append
方法:
up_result2 = l_u.join(r_u)
down_result2 = l_d.join(r_d)
result2=up_result2.append(down_result2)
#查看表头
result2.head()
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
Panads
的merge
方法和DataFrame
的append
方法:完成任务二和任务三的任务要有两个
DataFrame
都有的一列用于拼接:
默认参数是
False
,要改成True
,用行索引拼接
up_result3=pd.merge(l_u,r_u,left_index=True,right_index=True)
down_result3=pd.merge(l_d,r_d,left_index=True,right_index=True)
result3=up_result3.append(down_result3)
result3.head()
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
【思考】对比merge、join以及concat的方法的不同以及相同。思考一下在任务四和任务五的情况下,为什么都要求使用DataFrame的append方法,如何只要求使用merge或者join可不可以完成任务四和任务五呢?
DataFrame
对象concat
和append
默认使用纵向连接concat
将axis
参数变为1后,即可横向连接join
和merge
只能横向连接
merge
,append
,join
方法的区别
result.to_csv('result(practice).csv')
stack
函数会返回一个重构的数据
会将数据的列变为行
data=pd.read_csv("result(practice).csv")
data_series=data.stack()
data_series.head()
0 Unnamed: 0 0
PassengerId 1
Survived 0
Pclass 3
Name Braund, Mr. Owen Harris
dtype: object
stack():将列旋转到行
参考博客
是一种分组操作
参考一
参考二
如:统计平均年龄
group=df.groupby('Sex')
group.describe()
Unnamed: 0 | PassengerId | ... | Parch | Fare | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
count | mean | std | min | 25% | 50% | 75% | max | count | mean | ... | 75% | max | count | mean | std | min | 25% | 50% | 75% | max | |
Sex | |||||||||||||||||||||
female | 314.0 | 227.305732 | 132.683758 | 1.0 | 109.5 | 236.0 | 340.75 | 449.0 | 314.0 | 431.028662 | ... | 1.0 | 6.0 | 314.0 | 44.479818 | 57.997698 | 6.75 | 12.071875 | 23.0 | 55.00 | 512.3292 |
male | 577.0 | 219.571924 | 126.605257 | 0.0 | 112.0 | 219.0 | 330.00 | 451.0 | 577.0 | 454.147314 | ... | 0.0 | 5.0 | 577.0 | 25.523893 | 43.138263 | 0.00 | 7.895800 | 10.5 | 26.55 | 512.3292 |
2 rows × 64 columns
df.groupby('Sex')['Age'].describe()
count | mean | std | min | 25% | 50% | 75% | max | |
---|---|---|---|---|---|---|---|---|
Sex | ||||||||
female | 261.0 | 27.915709 | 14.110146 | 0.75 | 18.0 | 27.0 | 37.0 | 63.0 |
male | 453.0 | 30.726645 | 14.678201 | 0.42 | 21.0 | 29.0 | 39.0 | 80.0 |
计算平均值
:
df.groupby('Sex')['Age'].mean()
Sex
female 27.915709
male 30.726645
Name: Age, dtype: float64
fare_mean=df.groupby('Sex')['Fare'].mean()
下面通过几个任务来熟悉
GroupBy
机制。
survived=df.groupby('Sex')['Survived'].sum()
df.groupby('Pclass')['Survived'].sum()
Pclass
1 136
2 87
3 119
Name: Survived, dtype: int64
【思考】从数据分析的角度,上面的统计结果可以得出那些结论
【思考】从任务二到任务三中,这些运算可以通过agg()
函数来同时计算。并且可以使用rename
函数修改列名。你可以按照提示写出这个过程吗?
#agg可以使用多个
df.groupby('Sex').agg({'Survived':'sum','Fare':'mean'})
Survived | Fare | |
---|---|---|
Sex | ||
female | 233 | 44.479818 |
male | 109 | 25.523893 |
#修改列名
df.groupby('Sex').agg({'Survived':'sum','Fare':'mean'}).rename(columns ={'Survived':'存活人数','Fare':'平均船票费'})
存活人数 | 平均船票费 | |
---|---|---|
Sex | ||
female | 233 | 44.479818 |
male | 109 | 25.523893 |
df.groupby(['Pclass','Age'])['Fare'].mean()
Pclass Age
1 0.92 151.5500
2.00 151.5500
4.00 81.8583
11.00 120.0000
14.00 120.0000
...
3 61.00 6.2375
63.00 9.5875
65.00 7.7500
70.50 7.7500
74.00 7.7750
Name: Fare, Length: 182, dtype: float64
a = df.groupby(['Pclass', 'Age'])['Fare'].mean().head(2)
#转化为DataFrame才能merge
pd.merge(fare_mean.to_frame(),survived.to_frame(),on='Sex')
Fare | Survived | |
---|---|---|
Sex | ||
female | 44.479818 | 233 |
male | 25.523893 | 109 |
观察索引判断是否可以使用merge方法
fare_mean.index
Index(['female', 'male'], dtype='object', name='Sex')
survived.index
Index(['female', 'male'], dtype='object', name='Sex')
survived_age=df.groupby('Age')['Survived'].sum()
max(survived_age)
15
survived_age[survived_age.values==max(survived_age)]
Age
24.0 15
Name: Survived, dtype: int64
rate=max(survived_age)/sum(df['Survived'])
print('最大存活率:{}'.format(rate))
最大存活率:0.043859649122807015
观察索引判断是否可以使用merge方法
fare_mean.index
Index(['female', 'male'], dtype='object', name='Sex')
survived.index
Index(['female', 'male'], dtype='object', name='Sex')
survived_age=df.groupby('Age')['Survived'].sum()
max(survived_age)
15
survived_age[survived_age.values==max(survived_age)]
Age
24.0 15
Name: Survived, dtype: int64
rate=max(survived_age)/sum(df['Survived'])
print('最大存活率:{}'.format(rate))
最大存活率:0.043859649122807015