Home > Mobile >  How to use Condion to generate Excel files based on dataframe column values Python
How to use Condion to generate Excel files based on dataframe column values Python

Time:09-16

I want to create files based on below mentioned cells value except value "-"

for eg. if value == "-": Then don't create file. else: create file for remaining all values

  • i.e 642553, abc, 09pol_, -100
File
-
642553
abc
09pol_
-100

My code

for H_value in Health[columnName].unique():
        
        if H_value == '-':
            pass
        else:
            df1 = Health[Health[columnName] == H_value]
            output_file_name = "_"  str(H_value)   ".xlsx"
            output_file_name = os.path.join(newFolder, output_file_name)
            df1.to_excel(output_file_name, index=False)

This code creating files for all values

kindly help me for the same.

CodePudding user response:

Since you already know which column names to exclude, you can create a list beforehand containing all the values you wish to exclude, and then filter over that before initialising your for loop. Here's the code,

bad_values = ['-','abc','-100']
#~ inverses the selection, so in this case all values except bad_values will be selected 
for H_value in Health[~Health[ColumnName].isin(bad_values)][columnName].unique():

    df1 = Health[Health[columnName] == H_value]
    output_file_name = "_"  str(H_value)   ".xlsx"
    output_file_name = os.path.join(newFolder, output_file_name)
    df1.to_excel(output_file_name, index=False)

Hope this helps.

  • Related