亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

合并多索引熊貓數據幀

合并多索引熊貓數據幀

慕田峪7331174 2022-08-02 17:00:59
我有三個多索引熊貓數據幀 -df1 = {('parity', np.nan): {('20194', 1990): 0.3333333333333333,                            ('22204', 1990): 0.0,                            ('24060', 1990): 0.3333333333333333},       ('parity', 0.0): {('20194', 1990): 0.0,                         ('22204', 1990): 0.0,                         ('24060', 1990): 0.3333333333333333},       ('parity', 1.0): {('20194', 1990): 0.3333333333333333,                         ('22204', 1990): 1.0,                         ('24060', 1990): 0.0},       ('parity', 2.0): {('20194', 1990): 0.3333333333333333,                         ('22204', 1990): 0.0,                         ('24060', 1990): 0.3333333333333333},       ('education', 0.0): {('20194', 1990): 0.3333333333333333,                            ('22204', 1990): 0.6666666666666666,                            ('24060', 1990): 0.6666666666666666},       ('education', 1.0): {('20194', 1990): 0.6666666666666666,                            ('22204', 1990): 0.3333333333333333,                            ('24060', 1990): 0.3333333333333333}}df1 = pd.DataFrame(data = df1)df2 = {('parity', 'zip'): {0: '20194', 1: '22204', 2: '24060'},        ('parity', 'year'): {0: 1990, 1: 1990, 2: 1990},        ('parity', 'parity'): {0: 1.5, 1: 1.0, 2: 1.0}} df2 = pd.DataFrame(data = df2)df3 = {'parity': {('20194', 1990): 1.5, ('22204', 1990): 1.0, ('24060', 1990): 1.0},       'education': {('20194', 1990): 0.6666666666666666,                     ('22204', 1990): 0.3333333333333333,                     ('24060', 1990): 0.3333333333333333}}df3 = pd.DataFrame(data = df3)如何合并 索引和列上的所有數據框,使它們看起來像下圖?zipyear
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

將 concat 與 級別 和 in 索引以及列中的 2 個級別結合使用:MultiIndexzipyearMultiIndex


#convert columns to MultiIndex in index

df2 = df2.set_index([('parity','zip'),('parity','year')])

#created new MultiIndex in columns

df3.columns = pd.MultiIndex.from_product([df3.columns, ['new']])

df = pd.concat([df1, df2, df3],axis=1).rename_axis(['zip','year'])

print (df)

              parity                               education           parity  \

                 NaN       0.0       1.0       2.0       0.0       1.0 parity   

zip   year                                                                      

20194 1990  0.333333  0.000000  0.333333  0.333333  0.333333  0.666667    1.5   

22204 1990  0.000000  0.000000  1.000000  0.000000  0.666667  0.333333    1.0   

24060 1990  0.333333  0.333333  0.000000  0.333333  0.666667  0.333333    1.0   


                education  

            new       new  

zip   year                 

20194 1990  1.5  0.666667  

22204 1990  1.0  0.333333  

24060 1990  1.0  0.333333  


查看完整回答
反對 回復 2022-08-02
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號