python - Appending a multi-indexed column to the index of a DataFrame -


i have generated initial dataframe called df , adjusted dataframe called df_new.

i wish df df_new using set_index() operation. problem how negotiate hierarchical index on columns

import pandas pd import numpy np  df = pd.dataframe(np.ones((5,5))) col_idx = pd.multiindex.from_tuples([('x','a'),('x','b'),('y','c'),('y','d'),('y','e')]) row_idx = ['a1','a2','a3','a4','a5'] df.columns = col_idx df.index = row_idx idx = pd.indexslice df.loc[:,idx['y','d']] = 99 print df.head()       x     y             b  c   d  e a1  1  1  1  99  1 a2  1  1  1  99  1 a3  1  1  1  99  1 a4  1  1  1  99  1 a5  1  1  1  99  1  #------------------------------------------------------------------------------------------   df_new = pd.dataframe(np.ones((5,4))) col_idx = pd.multiindex.from_tuples([('x','a'),('x','b'),('y','c'),('y','e')]) row_idx = pd.multiindex.from_tuples([('a1',99),('a2',99),('a3',99),('a4',99),('a5',99)])  df_new.columns = col_idx df_new.index = row_idx print df_new.head()  # df_new should like. # ('y','d') got appended row index.         x     y            b  c  e a1 99  1  1  1  1 a2 99  1  1  1  1 a3 99  1  1  1  1 a4 99  1  1  1  1 a5 99  1  1  1  1 

the dataframe.set_index method takes append keyword argument, can this:

df_new = df.set_index(("y", "d"), append=true) 

if want add multiple columns, provide them list:

df_new = df.set_index([("y", "d"), ("y", "e")], append=true) 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -