0

I am fairly new to Python. I am leveraging Python's holidays package which has public holidays by country. I am looking to write a function that loops over any number of countries and returns a dataframe with 3 columns:

Date, Holiday, Country

Based on my limited knowledge, I came up with this sort of implementation:

import holidays
def getholidayDF(*args):
    holidayDF = pd.DataFrame(columns=['Date','Holiday','Country'])

    for country in args:
        holidayDF.append(sorted(holidays.CountryHoliday(country,years=np.arange(2014,2030,1)).items()))
        holidayDF['Country'] = country
        return holidayDF

holidays = getholidayDF('FRA', 'Norway', 'Finland', 'US', 'Germany', 'UnitedKingdom', 'Sweden')

This returns a blank dataframe. I am not sure how to proceed!

smci
  • 32,567
  • 20
  • 113
  • 146
biviz
  • 163
  • 8
  • 1
    You have `return` inside your `for` loop. That immediately breaks out of the function on the the first loop – roganjosh Feb 09 '20 at 22:14
  • Moving return out of for loop gave the same result. :/ – biviz Feb 09 '20 at 22:16
  • 2
    `holidayDF['Country'] = country` keeps reassigning a value to a the same key. Dictionary keys need to be unique. We'll be here a long time of we keep debugging like this; you should take a step back here and learn some python fundamentals – roganjosh Feb 09 '20 at 22:19
  • Variable and function names should follow the `lower_case_with_underscores` style. Appending to a DataFrame isn't great, you should really read the docs. What are you using the DataFrame for? – AMC Feb 09 '20 at 22:44
  • ..and many other examples you can find them [here](https://stackoverflow.com/questions/10715965/add-one-row-to-pandas-dataframe). – ZF007 Feb 09 '20 at 22:46

1 Answers1

0

If you change your for-loop as shown below it should be okay for you. Most relevant comments were made by user roganjosh. O'Reilly, Wrokx, Prentece Hall, Pearson, Packt.. just to name a few publishers... they have some good books for you. Skip the cookbooks for now.

.. code snippet ...

for country in args:
        holidayDF = holidayDF.append(sorted(holidays.CountryHoliday(country,years=np.arange(2014,2030,1)).items()))
 #       holidayDF['Country'] = country  # remove this from the for-loop.
return holidayDF  # move out of the for-loop
ZF007
  • 3,708
  • 8
  • 29
  • 48