0

For the life of me I can't figure out how to use multiindex or any other way to make more than one vertical header for a column. This is the code I have:

import pandas as pd
    
genderad = [['Prescribed Taking', 1458, 4404, 14, 'Prescribed Taking', 1558, 4270, 26], ['Prescribed Not Taking', 226, 781, 1, 'Prescribed Not Taking', 171, 523, 2], ['Not Prescribed', 2302, 6672, 35, 'Not Prescribed', 1899, 4330, 26]]
df = pd.DataFrame(genderad)
df = pd.DataFrame(genderad, columns = ['Medication Status', 'Male', 'Female', 'Z', 'Medication Status', 'Male', 'Female', 'Z'])
df

This code leads me to this table: https://i.sstatic.net/NRT0I.png

What I'm trying to figure out is how I can possibly add another header titled 'Depression' above the first section of Medication Status, Male, Female, & Z, while adding another header titled 'Anxiety' above the second section of Medication Status, Male, Female, & Z.

Otherwise, if it's possible, I could just make the existing headers just part of the table and if possible merge? the first four rows and title that depression and do the same with the other four rows except labelling it as anxiety?

I'd really appreciate any help I can get as I'm quite new to pandas. Thanks.

2 Answers 2

1

You want to use a MultiIndex for the columns:

columns = pd.MultiIndex.from_product((['Depression', 'Anxiety'],
                                      ['Medication Status', 'Male', 'Female', 'Z']))
df = pd.DataFrame(genderad, columns=columns)

It gives for print(df.to_string()):

              Depression                                 Anxiety                 
       Medication Status  Male Female   Z      Medication Status  Male Female   Z
0      Prescribed Taking  1458   4404  14      Prescribed Taking  1558   4270  26
1  Prescribed Not Taking   226    781   1  Prescribed Not Taking   171    523   2
2         Not Prescribed  2302   6672  35         Not Prescribed  1899   4330  26
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Just wanted to ask is there any way to center the text? e.g. In the table you displayed in your answer, Depression and Anxiety are centered. Is this possible?
0

You can do something like this:

df.columns = pd.MultiIndex.from_tuples(zip(['Depression']*4+['Anxiety']*4, df.columns))

Which will result in a dataframe looking like:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.