offthehook
offthehook

Reputation: 73

How to place existing columns under a hierarchy?

My imported data from excel has been multi indexed with the time stamp column in Pandas. I would like place the remaining columns into their respective hierarchical groups. The frequency band columns (7 columns: delta', 'theta', 'alpha', 'beta', 'high beta', 'gamma') under the hierarchy column labeled 'EMG' and the biological measures (2 columns: 'Heart Rate Variabilty' and 'GSR') under 'Biofeedback'.

Is there a straight forward way to do this?

The second part is, how can a single level dataframe be appended to this multi index hierarchical dataframe without flattening the hierarchy created in the first part?

Upvotes: 1

Views: 209

Answers (1)

jezrael
jezrael

Reputation: 863031

You can create MultiIndex.from_arrays and then reindex:

cols = ['delta','theta','alpha','beta','Heart Rate Variabilty','high beta', 'gamma','GSR']
df = pd.DataFrame([[4,5,8,3,1,0,9,2]], columns=cols)    
print (df)
   delta  theta  alpha  beta  Heart Rate Variabilty  high beta  gamma  GSR
0      4      5      8     3                      1          0      9    2   

c1 = ['delta', 'theta', 'alpha', 'beta','high beta', 'gamma']
c2 = ['Heart Rate Variabilty', 'GSR']  


mux = pd.MultiIndex.from_arrays([ ['EMG'] * len(c1) + ['Biofeedback'] * len(c2),c1 + c2])
print (mux)
MultiIndex(levels=[['Biofeedback', 'EMG'], 
                   ['GSR', 'Heart Rate Variabilty', 'alpha', 'beta',
                    'delta', 'gamma', 'high beta', 'theta']],
           labels=[[1, 1, 1, 1, 1, 1, 0, 0], [4, 7, 2, 3, 6, 5, 1, 0]])

df = df.reindex(columns=mux, level=1)
print (df)
    EMG                                            Biofeedback    
  delta theta alpha beta high beta gamma Heart Rate Variabilty GSR
0     4     5     8    3         0     9                     1   2

EDIT by comment:

Thank you for final solution OP:

df1.columns = pd.MultiIndex.from_tuples([(c, '', '') for c in df1])
df = pd.concat([df, df1], axis=1)

Upvotes: 1

Related Questions