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.stack.imgur.com/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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.