在python中使用multiindex合并多个数据框 [英] Merge multiple dataframes using multiindex in python

查看:775
本文介绍了在python中使用multiindex合并多个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个序列,这些序列是由下面的代码生成的.我在下面显示了一个系列的代码

I have 3 series which is generated out of the code shown below. I have shown a the code for one series below

我想使用列(subject_id,hadm_id,icustay_id)合并3个这样的系列/数据框,但是不幸的是这些标题没有显示为列名.如何将它们转换为列,并用于与相似数据类型的另一个系列/数据框合并

I would like to merge 3 such series/dataframes using columns (subject_id,hadm_id,icustay_id) but unfortunately these headings don't appear as column names. How do I convert them as columns and use them for merging with another series/dataframe of similar datatype

我正在根据下面给出的条件从另一个数据帧(df)生成序列.尽管我已经尝试过将这个系列转换为数据框,但是它仍然不显示索引,而是将列名显示为索引.我已经在下面显示了输出.我想将值'Subject_id','hadm_id','icustay_id'与其他列'val_bw_80_110'一起作为数据帧中的列名看到,以便我可以使用这3个ID('Subject_id','hadm_id' ,'icustay_id')

I am generating series from another dataframe (df) based on the condition given below. Though I already tried converting this series to dataframe, still it doesn't display the indices, instead it displays the column name as index. I have shown the output below. I would like to see the values 'Subject_id','hadm_id','icustay_id' as column names in dataframe along with other column 'val_bw_80_110' so that I can join with other dataframes using these 3 ids ('Subject_id','hadm_id','icustay_id')

s1 = 
df.groupby(['subject_id','hadm_id','icustay_id'['val_bw_80_110'].mean()

我期望输出将id(subject_id,hadm_id,icustay_id)转换为列名,并可以将其用于其他数据框的合并/合并.

I expect an output where the ids (subject_id,hadm_id,icustay_id) are converted to column names and can be used for joining/merging with other dataframes.

推荐答案

您可以将参数as_index=False添加到

You can add parameter as_index=False to DataFrame.groupby or use Series.reset_index:

df = df.groupby(['subject_id','hadm_id','icustay_id'], as_index=False)['val_bw_80_110'].mean()

或者:

df = df.groupby(['subject_id','hadm_id','icustay_id'])['val_bw_80_110'].mean().reset_index()

这篇关于在python中使用multiindex合并多个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆