第二章:数据重构
# 导入数据
text = pd.read_csv('result.csv')
2.4 数据的合并
方法1:concat函数
方法2:join方法和DataFrame的append方法
方法3:使用Panads的merge方法和DataFrame的append方法
2.4.1 将data文件夹里面的所有数据都载入,观察数据的之间的关系
text_left_up = pd.read_csv("data/train-left-up.csv")
text_left_down = pd.read_csv("data/train-left-down.csv")
text_right_up = pd.read_csv("data/train-right-up.csv")
text_right_down = pd.read_csv("data/train-right-down.csv")
# 查看前5行数据
text_left_up.head()
text_left_down.head()
text_right_down.head()
text_right_up.head()
2.4.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)
#使用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) # 上下添加
#使用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)
2.5 换角度看数据
unit_result = text.stack().head(20)
# 把每一行的数据进行堆叠
2.6 数据运用
2.6.1 Groupby机制
将一列相同的特征分组,每一特征分为一组,可以进行分组计算。
2.6.2 计算泰坦尼克号男性与女性的平均票价
df = text['Fare'].groupby(text['Sex'])
means = df.mean()
2.6.3 统计泰坦尼克号中男女的存活人数
df = text['Survived'].groupby(text['Sex']).sum()
2.6.4 计算客舱不同等级的存活人数
survived_pclass = text['Survived'].groupby(text['Pclass']).sum()
# 通过agg()函数来同时计算。并且可以使用rename函数修改列名
text.groupby('Sex').agg({'Fare':'mean', 'Pclass':'count'}).rename(columns=
{'Fare':'mean_fare','Pclass':'count_pclass'})
2.6.5 统计在不同等级的票中的不同年龄的船票花费的平均值
text.groupby(['Pclass','Age'])['Fare'].mean().head()
2.6.6 将任务二means和任务三的数据Sex合并,并保存到sex_fare_survived.csv
# 性别作为表头
result = pd.merge(means, df, on='Sex')
2.6.7 得出不同年龄的总的存活人数,然后找出存活人数最多的年龄段,最后计算存活人数最高的存活率(存活人数/总人数)
# 不同年龄的存活人数
survived_age = text['Survived'].groupby(text['Age']).sum()
# 找出最大值的年龄段
survived_age[survived_age.values==survived_age.max()]
# ——sum
_sum = text['Survived'].sum()
#最大存活率
precent = survived_age.max()/_sum
print("最大存活率:"+str(precent))