简体   繁体   中英

Create multiple sheets in excel using pandas to loop through sheet names

I am trying to create multiple sheets in excel, using pandas integration with xlsxwriter in Python, based on data represented in categories

Categories ="Autoimmune Diseases","Blood","Cancer: Head & Neck","Cancer: Hematological","Cancer: Other","Cardiovascular","Dermatological Treatment","Eyes","Immune Deficiencies","Infectious Diseases","Liver Disease","Neurological","Neurotology","Pain Management","Rare Diseases","Respiratory Diseases","Women's Health"

Right now my code looks like:

writer = pd.ExcelWriter(Individualreport, engine='xlsxwriter')
Categories ="Autoimmune Diseases","Blood","Cancer: Head & Neck","Cancer: Hematological","Cancer: Other","Cardiovascular","Dermatological Treatment","Eyes","Immune Deficiencies","Infectious Diseases","Liver Disease","Neurological","Neurotology","Pain Management","Rare Diseases","Respiratory Diseases","Women's Health"

Overview = pd.read_excel(READ,sheet_name='Overview', header=None)
OverviewCols = pd.read_excel(READ, sheet_name='Overview', header=None,nrows=1).values[0]
Overview.columns = OverviewCols

auto = Overview.loc[(Overview['Category']=="Autoimmune Diseases")]
auto.to_excel(writer, sheet_name='Auto', startrow= over_row, startcol=over_col, header=False, index=False)

and I would have to repeat for all 17 categories to make each sheet like:

blood = Overview.loc[(Overview['Category']=="Blood")]
blood.to_excel(writer, sheet_name='Blood', startrow= over_row, startcol=over_col, header=False, index=False)

Is there a way to loop through the list to simplify the code? I know this isn't right, but something like:

for i in Categories:
    i = Overview.loc[(Overview['Category']==i)]
    i.to_excel(writer, sheet_name=i, startrow= over_row, startcol=over_col, header=False, index=False)

referring to your code:

for i in Categories:
    i = Overview.loc[(Overview['Category']==i)]
    i.to_excel(writer, sheet_name=i, startrow= over_row, startcol=over_col, header=False, index=False)

The variable "Categories" is a tuple of strings - you are trying to use a string "i" as a variable eg:

"Blood" = Overview.loc[(Overview['Category']=="Blood")

which won t work.

Have your tried to use a free variable name?

for cat in Categories:
    test = Overview.loc[(Overview['Category']==cat)]
    test.to_excel(writer, sheet_name=cat, startrow=over_row, startcol=over_col, header=False, index=False)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM