数据重构
数据合并
①使用concat()函数
部分参数如下
参数 | 说明 |
---|---|
obj | DataFrame对象/Series对象 |
axis | 0为纵向,1为横向 |
join | 如何处理其他轴上的索引。outer为联合;inner为交集,即只合并有相同列/行的部分 |
ignore_index | boolean,为True则重新设置合并后的index,False则直接拼接,不修改原有索引 |
result_up = pd.concat([dflu,dfru],axis=1)
result_down = pd.concat([dfld,dfrd],axis=1)
result = pd.concat([result_up,result_down])
②使用join()和append()方法实现数据合并
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)
③使用pandas自带merge()函数和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)
将数据保存为Series对象
stack()方法会把数据的列旋转为行,使DataFrame对象转换为Series对象
unit_result=result.stack()
数据运用
Groupby分组机制
Groupby就是将数据按提供的键值分组拆分,然后按各个键值所需要的数据应用计算,最后再重新合并为一个DataFrame对象。如下图:
使用groupby()方法即可生成Groupby对象,利用agg()方法可以同时计算
# 使用单一特征单一方法
df.groupby('Sex')['Survived'].count()
# 使用多个特征同时分组
df.groupby(['Sex','Pclass']).agg({'Fare':'mean','Survived':'sum'}).rename({'Fare':'mean_fare','Survived':'sum_survived'})