Merge multiple dataframes using multiindex in python

我与影子孤独终老i 提交于 2019-12-24 10:23:46

问题


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

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

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()

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.


回答1:


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()

Or:

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


来源:https://stackoverflow.com/questions/55592014/merge-multiple-dataframes-using-multiindex-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!