I have 2 pandas DataFrames act and exp that I want to combine into a single dataframe df:
import pandas as pd
from numpy.random import rand
act = pd.DataFrame(rand(3,2), columns=['a', 'b'])
exp = pd.DataFrame(rand(3,2), columns=['a', 'c'])
act #have
a b
0 0.853910 0.405463
1 0.822641 0.255832
2 0.673718 0.313768
exp #have
a c
0 0.464781 0.325553
1 0.565531 0.269678
2 0.363693 0.775927
Dataframe df should contain one more column index level than act and exp, and contain each under its own level-0 identifier, like so:
df #want
act exp
a b a c
0 0.853910 0.405463 0.464781 0.325553
1 0.822641 0.255832 0.565531 0.269678
2 0.673718 0.313768 0.363693 0.775927
Any ideas as to how to do this?
It's a bit like mergeing the two frames:
act.merge(exp, left_index=True, right_index=True, suffixes=['_act', '_exp'])
a_act b a_exp c
0 0.853910 0.405463 0.464781 0.325553
1 0.822641 0.255832 0.565531 0.269678
2 0.673718 0.313768 0.363693 0.775927
...but using an additional level, instead of a suffix, to prevent name collisions.
I tried:
#not working
pd.DataFrame({'act': act, 'exp':exp})
I could use loops to build up the df series-by-series, but that doesn't seem right.
Many thanks.