Reputation: 173
I am fairly new to Python. I am leveraging Python's holiday package which has public holidays by country. In order to get a country's holiday, you can run something like:
sorted(holidays.US(years=np.arange(2014,2030,1)).items()
This will give the date and holiday. Now, I want the data against a bunch of countries. How do I loop over the list of countries instead of replacing the country name in the above code every single time? the countries under consideration here are:
[FRA, Norway, Finland, US, Germany, UnitedKingdom, Sweden]
I tried a for loop like this:
countrylistLoop = ['FRA', 'Norway', 'Finland', 'US', 'Germany', 'UnitedKingdom', 'Sweden']
for i in countrylistLoop:
print(sorted(holidays.i(years=np.arange(2014,2030,1)).items()),columns=['Date','Holiday'])
This throws an AttributeError:
AttributeError: module 'holidays' has no attribute 'i'.
This makes sense but I am not sure how to proceed!
Ideally, I would like to loop over and store the results in a dataframe. Any help is highly appreciated! Thank you!
Upvotes: 2
Views: 2768
Reputation: 5610
for i in countrylistLoop:
holiday = getattr(holidays, i)(years=np.arange(2014,2030,1)).items()
sorted(holiday)
print(holiday)
To get an attribute dynamically, use getattr
.
Otherwise, I split the sorted
function out because it returns None
, as all mutating builtins for python do.
Upvotes: 0
Reputation: 11
To provide an additional country identifier you can do this:
all_holidays = []
country_list = ['UnitedStates', 'India', 'Germany']
for country in country_list:
for holiday in holidays.CountryHoliday(country, years = np.arange(2018,2021,1)).items():
all_holidays.append({'date' : holiday[0], 'holiday' : holiday[1], 'country': country})
all_holidays = pd.DataFrame(all_holidays)
all_holidays
The result will be: enter image description here
Upvotes: 1
Reputation: 1956
You could get the items the following way
import holidays
countrylistLoop = ['FRA', 'Norway', 'Finland', 'US', 'Germany', 'UnitedKingdom', 'Sweden']
for country in countrylistLoop:
hd = sorted(holidays.CountryHoliday(country, years=np.arange(2014,2030,1)).items())
But it doesn't take the columns
argument for sorted.
or you can sort items based on the index
hd = sorted(list(holidays.CountryHoliday(country,
years=np.arange(2014,2030,1)).items()),
key=lambda holiday: holiday[1])
Upvotes: 5