Home > database >  how to loop by each value in python
how to loop by each value in python

Time:05-25

Below is the code where I want to filter in the data frame through the country list in a loop. how to pass that value in the Owning country filter?

This is my Code :

countrylist= ['Italy','Germany']
for country in countrylist:
        dataframe = dataframe[dataframe['Owning_Country'] == ]

Thanks

CodePudding user response:

Try this out:

countrylist= ['Italy','Germany']

for country in countrylist:

df= df[df['Owning_Country'] == country]

CodePudding user response:

you may have to use sleep from time module i guess.

import time

countrylist= ['Italy','Germany']
for country in countrylist:
    print(country)
    time.sleep(1)
    dataframe = dataframe[dataframe['Owning_Country'] == country]

maybe sommeone can provide a better way but as so far this is the simplest way.

CodePudding user response:

Thanks all, but i tried the below and it worked

countrylist= ['Italy','Germany']

for country in countrylist:

    dataframe = dataframe[dataframe['Owning_Country].isin()countrylist]

but now i am stuck with how to print output of that in seprate excel sheets in one workbook. i tried the below but didnt work

output.to_excel(writer, sheet_name ='Country{0}_{1}'.format(country))

  • Related