Dataframe中按id将同一id的不同行变换成一行
问题:将如下图1按照s_info_windcode转换成图2
解决方法:先对df进行s_info_windcode的groupby,然后进行unstack操作,columns重命名
方法一:代码简练,但有点难懂
分开展示
方法二:容易理解,但偏机械
b = aa.copy() df1 = pd.DataFrame(b.groupby('s_info_windcode')['f_prt_stocktotot'].apply(list)) stock = df1['f_prt_stocktotot'].apply(pd.Series).rename(columns=lambda x:'stocktotot'+str(x+1)) #axis=1 #apply(pd.Series)就会按列分开,每列重命名 stock.head() df2 = pd.DataFrame(b.groupby('s_info_windcode')['f_prt_bondtotot'].apply(list)) bond = df2['f_prt_bondtotot'].apply(pd.Series).rename(columns=lambda x:'bond'+str(x+1)) bond.head() pd.merge(stock,bond,on='s_info_windcode')
发现了自己之前的写法觉得好low
# cmfassetportfolio_1 = cmfassetportfolio[(cmfassetportfolio['f_prt_enddate']=='2019-09-30')] # cmfassetportfolio_2 = cmfassetportfolio[(cmfassetportfolio['f_prt_enddate']=='2019-06-30')] # cmfassetportfolio_3 = cmfassetportfolio[(cmfassetportfolio['f_prt_enddate']=='2019-03-31')] # cmfassetportfolio_4 = cmfassetportfolio[(cmfassetportfolio['f_prt_enddate']=='2018-12-31')] # cmfassetportfolio_5 = cmfassetportfolio[(cmfassetportfolio['f_prt_enddate']=='2018-09-30')] # dt12 = pd.merge(cmfassetportfolio_1,cmfassetportfolio_2,on='s_info_windcode',how='outer',suffixes=('_1','_2')) # dt34 = pd.merge(cmfassetportfolio_3,cmfassetportfolio_4,on='s_info_windcode',how='outer',suffixes=('_3','_4')) # dt1234 = pd.merge(dt12,dt34,on='s_info_windcode',how='outer') # dt = pd.merge(dt1234,cmfassetportfolio_5,on='s_info_windcode',how='outer')
既然无论如何时间都会过去,为什么不选择做些有意义的事情呢