Apply Custom Functions
Learn how to apply custom functions to DataFrames.
Need for custom functions
In the course of running mathematical operations on our numerical data, there may be occasions where we want to apply a custom function on the data elements. For example, converting temperature values from Fahrenheit to Celsius is based on the following formula:
There is no native way to perform this conversion in pandas
, therefore the only way is to apply this mathematical formula to our numerical data, which we can easily do so with the apply()
and applymap()
methods.
The apply()
method
The apply()
method is used to apply a function along either the rows or columns of a DataFrame. It can also be used on a pandas
Series
object, though we will primarily focus on DataFrames. Let’s say we have the monthly average temperature in Fahrenheit for Athens between January and June. We can use the following code to generate a new column displaying the corresponding Celsius temperature:
# Define custom function for temperature conversiondef convert_fahrenheit_to_celsius(x):celsius_val = (x - 32) * (5/9)return round(celsius_val)# Apply custom function at row level (axis=1)df['Temp_C'] = df['Temp_F'].apply(convert_fahrenheit_to_celsius)print(df)
Let's use another example with multiple DataFrame columns. Suppose we have the following dataset of four students’ examination scores across four academic subjects, with the Student column set as the index.
Preview of Student Grades Dataset
Student | Math | Physics | History | Chemistry |
Aldon | 85 | 83 | 88 | 80 |
Britney | 93 | 90 | 92 | 95 |
Carlos | 65 | 63 | 68 | 61 |
Daisy | 70 | 71 | 75 | 77 |
If we want to create a new column that stores the difference between each ...
Get hands-on with 1400+ tech skills courses.