Skip to content Skip to sidebar Skip to footer

Create Multiindexed Dataframe Through Constructor

Given two arrays: x [('010_628', '2543677'), ('010_228', '2543677'), ('015_634', '2543677')] y array([['me', 10228955], ['me', 10228955], ['me', 10228955]], dtype=o

Solution 1:

You could use pd.MultiIndex.from_arrays(y.T):

In [53]: pd.DataFrame(x, index=pd.MultiIndex.from_arrays(y.T), columns=['pm_code',   'sec_pm'])
Out[53]: 
             pm_code   sec_pm
me 10228955010_628  254367710228955010_228  254367710228955015_634  2543677

or pd.MultiIndex.from_tuples(y.tolist()):

In [54]: pd.DataFrame(x, index=pd.MultiIndex.from_tuples(y.tolist()), columns=['pm_code',   'sec_pm'])
Out[54]: 
             pm_code   sec_pm
me 10228955010_628  254367710228955010_228  254367710228955015_634  2543677

Solution 2:

You can also slice your arrays and pass to index:

df = pd.DataFrame(x, index=[y[:,0], y[:,1]], columns=['pm_code',   'sec_pm'])

df
             pm_code   sec_pm
me 10228955  010_628  2543677
   10228955  010_228  2543677
   10228955  015_634  2543677

Solution 3:

Option 1 If you pass a list of arrays like things, the constructor knows what to do with it.

pd.DataFrame(x, index=y.T.tolist(), columns=['pm_code', 'sec_pm'])

    pm_code   sec_pm
me 10228955010_628  254367710228955010_228  254367710228955015_6342543677

Post a Comment for "Create Multiindexed Dataframe Through Constructor"