Python 合并多索引数据帧
我有三个多索引数据帧-Python 合并多索引数据帧,python,pandas,Python,Pandas,我有三个多索引数据帧- df1 = {('parity', np.nan): {('20194', 1990): 0.3333333333333333, ('22204', 1990): 0.0, ('24060', 1990): 0.3333333333333333}, ('parity', 0.0): {('20194', 1990): 0.0,
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)
如何合并zip
和year
索引和列上的所有数据帧,使它们看起来像下图?
与多索引
一起使用,索引中有级别zip
和year
,列中有两个级别多索引
:
#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
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)
#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