接上篇动手学数据分析 | 数据清洗及特征处理(二),下面代码为本篇内容的基本代码准备工作。
目录
一、数据的合并
观察数据
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()
text_left_down.head()
text_right_down.head()
text_right_up.head()
合并数据
使用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()
pd.concat(objs, axis=0, join=‘outer’)
其中objs表示需要连接的对象,需将合并的数据用[]包围;axis=0表拼接方式是上下堆叠,axis=1表示左右拼接;join参数控制的是outer外连接还是inner内连接,外连接保留两个表中的所有信息;内连接只保留两个表共有的信息。
将train-left-down和train-right-down横向合并为一张表,并保存这张表为result_down:
list_down=[text_left_down,text_right_down]
result_down = pd.concat(list_down,axis=1)
将result_up和result_down纵向合并为result:
result = pd.concat([result_up,result_down])
result.head()
使用DataFrame自带的join和append方法完成数据合并的任务:
result_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 = result_up.append(result_down)
result.head()
result.to_csv('result.csv')
df.append(other, ignore_index=False, verify_integrity=False, sort=False)
other:调用方要追加的其他DataFrame或者类似序列内容。可以放入一个由DataFrame组成的列表,将所有DataFrame追加起来;ignore_index:如果为True,则重新进行自然索引;verify_integrity:如果为True,则遇到重复索引内容时报错;sort:进行排序。
【拓展】对比merge、join的不同以及相同。
.join()着重关注的是行行的合并;.merge()着重关注的是列列的合并。关于这两个函数可参考博客pd.merge() pd.join_每天都要被自己菜醒的博客-CSDN博客。
二、转换数据类型
text = pd.read_csv('result.csv')
text.head()
unit_result = text.stack().head(20)
unit_result.head()
# 0 Unnamed: 0 0
# PassengerId 1
# Survived 0
# Pclass 3
# Name Braund, Mr. Owen Harris
# dtype: object
stack意为堆叠,stack()函数主要有两个参数:
第一个是需要堆叠的多个数组,采用列表的形式输入,如np.stack([arrays1,array2,array3],axis=0);第二个参数是axis,表示从哪个维度进行堆叠以及堆叠的内容,是相对于堆叠的数组来说的。整个函数的输出为一个新数组。
axis为0表示堆叠方向为第0维,堆叠内容为数组第0维的数据,其实就是整个3×4的数组(其中第1维为行,第2维为某行中的一个值),所以就是以整个3×4的数组为堆叠内容在第0维上进行堆叠,结果就是一个3×3×4的新数组。
此处参考np.stack()函数详解_冬天的东_的博客-CSDN博客_np.stack函数(这篇写的特别通俗易懂)
将代码保存为unit_result,csv:
unit_result.to_csv('unit_result.csv')
test = pd.read_csv('unit_result.csv')
test.head()
三、GroupBy数据运用
计算泰坦尼克号男性与女性的平均票价:
df = text['Fare'].groupby(text['Sex'])
means = df.mean()
means
# Sex
# female 44.479818
# male 25.523893
# Name: Fare, dtype: float64
统计泰坦尼克号中男女的存活人数:
survived_sex = text['Survived'].groupby(text['Sex']).sum()
survived_sex.head()
# Sex
# female 233
# male 109
# Name: Survived, dtype: int64
计算客舱不同等级的存活人数:
survived_pclass = text['Survived'].groupby(text['Pclass'])
survived_pclass.sum()
# Pclass
# 1 136
# 2 87
# 3 119
# Name: Survived, dtype: int64
前两个任务如何通过agg()函数来同时计算(并且可以使用rename函数修改列名)?
text.groupby('Sex').agg({'Fare': 'mean', 'Pclass': 'count'}).rename(columns=
{'Fare': 'mean_fare', 'Pclass': 'count_pclass'})
# mean_fare count_pclass
# Sex
# female 44.479818 314
# male 25.523893 577
统计在不同等级的票中的不同年龄的船票花费的平均值:
text.groupby(['Pclass','Age'])['Fare'].mean().head()
# Pclass Age
# 1 0.92 151.5500
# 2.00 151.5500
# 4.00 81.8583
# 11.00 120.0000
# 14.00 120.0000
# Name: Fare, dtype: float64
将任务一和二的数据合并,并保存到sex_fare_survived.csv
result = pd.merge(means, survived_sex, on='Sex')
result
# Fare Survived
# Sex
# female 44.479818 233
# male 25.523893 109
result.to_csv('sex_fare_survived.csv')
得出不同年龄的总的存活人数,找出存活人数最多的年龄段,计算存活人数最高的存活率(存活人数/总人数):
#不同年龄的存活人数
survived_age = text['Survived'].groupby(text['Age']).sum()
survived_age.head()
# Age
# 0.42 1
# 0.67 1
# 0.75 2
# 0.83 2
# 0.92 1
# Name: Survived, dtype: int64
找出最大值的年龄段:
survived_age[survived_age.values==survived_age.max()]
# Age
# 24.0 15
# Name: Survived, dtype: int64
首先计算总人数:
_sum = text['Survived'].sum()
print("sum of person:"+str(_sum)) #sum of person:342
计算存活率:
precetn = survived_age.max()/_sum
print("最大存活率:"+str(precetn)) #最大存活率:0.043859649122807015