Creating a function to convert a month number to the season

Allan Bond
3 min readFeb 7, 2021

I was trying to do some analysis on climate data where I have a DataFrame with various date columns (Year, Month, Day) and I was feeling like I was missing some aggregating factor that could help me better visualise the trends over the years that is not as broad as year but not as granular as month. Then I thought, “why not seasons?” — if there is a difference it would be by season, not by month.

I decided to write a quick function that would allow me to reliably do this. It was not quick. It had me stumped for a few hours while I tried different variations of my code.

I didn’t want to go down the if, elif path for every month, so I sought the knowledge of Stack Overflow to see if there was something I was missing after getting yet another TypeError exception.

The first thing I did was create a test DataFrame containing a column of months in it that I could use to easily check if my function works.

After creating the test DataFrame I wrote the function that would take the month number and the hemisphere and convert it into the correct season.

If you used this script by manually inputting the month number and hemisphere (i.e. 1 and Southern = Summer | 1 and Northern = Winter) then it would simply print the corresponding season. However, I discovered that using it to create a new column in a pandas DataFrame required a little more work than just calling the function on the target column.

The improved code above uses the function to fill a new list with the corresponding seasons, which can then be assigned to the Seasons column in the target DataFrame.

Final DataFrame showing the original Month column and the calculated Season column. Image by Author.

Future improvements would be to implement a handler for month names and abbreviations, in addition to the existing numbers.

I hope this brief guide is helpful to someone out there as it has been a learning experience for me and improved my understanding of Pandas DataFrames and designing functions for Python.

--

--

Allan Bond

Data science enthusiast with a passion for solving problems using my knowledge in Biotechnology, Business Administration and Data Science.