1

I have the following dataframe with datetime index:

>df

                     DEtoDK    DKtoDE  
datetime                           
2021-01-01 00:00:00  2500.0    2500.0
2021-01-01 01:00:00  2500.0    2500.0
2021-01-01 02:00:00  2500.0    2500.0

however, I don't like how it looks like and it restricts me calling two column values together (for example I want to call DEtoDK and DKtoDE together). Therefore I would like to group two columns DEtoDK and DKtoDE together into a master column A.

How can I do that?

Expected Outcome:

>df
                     A                   
                     DEtoDK    DKtoDE
datetime                           
2021-01-01 00:00:00  2500.0    2500.0
2021-01-01 01:00:00  2500.0    2500.0
2021-01-01 02:00:00  2500.0    2500.0

EDIT:

It can be done easily by Multi-Column by tuples via How to do Multi-Column from_tuples? , however if I don't have tuples is it not possible?

oakca
  • 1,408
  • 1
  • 18
  • 40

1 Answers1

0

You can use integer division by helper np.arange by lenght of columns by 2 and then convert integers to letter s by chr and ord functions, last pass to MultiIndex.from_arrays:

a = [chr(ord('A') + x) for x in np.arange(len(df.columns)) // 2]

df.columns = pd.MultiIndex.from_arrays([a, df.columns])
print (df)
                           A                 B         
                    A_DEtoDK A_DKtoDE B_DEtoDK B_DKtoDE
datetime                                               
2021-01-01 00:00:00   2500.0   2500.0    500.0    500.0
2021-01-01 01:00:00   2500.0   2500.0    500.0    500.0
2021-01-01 02:00:00   2500.0   2500.0    500.0    500.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • the `'_'` was just for visualisation. I don't really have that in my dataframe. – oakca Mar 15 '21 at 12:35
  • @oakca - hmmm, so it means need split by first letter and all another letters? – jezrael Mar 15 '21 at 12:37
  • Imagine every 2 column is a group, and I want to set a master column name for each 2 columns. More easily imagine I have only 2 columns and I need to set 1 master column for both of these columns – oakca Mar 15 '21 at 12:37
  • @oakca - It is possibe numbers like `0,0,1,1,2,2..` ? – jezrael Mar 15 '21 at 12:38
  • I would prefer a string instead of numbers, updated question @jezrael – oakca Mar 15 '21 at 12:39