简体   繁体   中英

Multiple data frames - Wide to long using pandas

I have two data frames like as shown below

df1 = pd.DataFrame({'person_id': [11, 21, 31, 41, 51],
                        'date_1': ['12/30/1961', '05/29/1967', '02/03/1957', '7/27/1959', '01/13/1971'],
                        'date_2': ['07/23/2017','05/29/2017','02/03/2015',np.nan,np.nan]})

df2 = pd.DataFrame({'person_id': [11,11,11,21,31],
                    'visit_id':['A1','A2','A3','B1','B2'],
                    'date_start': ['01/01/2012', '02/25/2017', '02/03/2015', '07/27/2016', '01/13/2011'],
                    'date_end': ['05/03/2012','05/29/2017','03/03/2015','08/15/2016','02/13/2011']})

I tried the below. I want only the date columns in a long format

df = pd.merge(df1, df2, on='person_id',how='outer')
df = pd.wide_to_long(df, stubnames=['date'], i='person_id', j='grp').sort_index(level=0)
df = df.reset_index(level=1, drop=True).reset_index()
df

But this gives an empty data frame.

I would like to get all the dates of each subject as shown below (sample output for 2 subjects)

在此处输入图像描述

This is just melt and concat :

(pd.concat([df1.melt('person_id', value_name='dates'), 
            df2.melt('person_id',value_vars=['date_start','date_end'], value_name='dates')
          ])
   .drop('variable', axis=1)
   .sort_values('person_id')
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM