Passing an array of countries to a function

余生长醉 提交于 2020-02-23 07:14:27

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/60141847/passing-an-array-of-countries-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!