Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add a title to a dataframe spanning across multiple columns?

Tags:

python

pandas

Let's say you have any pandas dataframe with 4 columns, and you want to add a header row to it. Is there a way to do this?

Here is an example dataframe for you to work with:

pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

enter image description here

I'd like to add something on top like the September header above.

like image 452
pr338 Avatar asked Oct 11 '25 08:10

pr338


1 Answers

You need MultiIndex here

df=pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD'))
df.columns=pd.MultiIndex.from_product([['Sep'],df.columns])
df
Out[666]: 
  Sep            
    A   B   C   D
0  33  91  64  27
1  46   5  32  40
2  64  55  13  13
3  65  80  82  64
4  78  21  55  10
5  15  15  55  32
6  65  18  11  30
7  32  37  83   8
8  82  59   2  87
9   9  69  56  70
like image 124
BENY Avatar answered Oct 16 '25 08:10

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!