Apply Function
In [1]:
# Applying a Function to Each Element in a Column
import pandas as pd
data = {
'temperature_celsius': [0, 20, 30, 40]
}
df = pd.DataFrame(data)
#######################################
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
#######################################
df['temperature_fahrenheit'] = df['temperature_celsius'].apply(celsius_to_fahrenheit)
print(df)
temperature_celsius temperature_fahrenheit 0 0 32.0 1 20 68.0 2 30 86.0 3 40 104.0
In [2]:
# Applying a Lambda Function
import pandas as pd
data = {
'names': ['Alice', 'Bob', 'Charlie', 'David']
}
df = pd.DataFrame(data)
df['name_length'] = df['names'].apply(lambda x: len(x))
print(df)
names name_length 0 Alice 5 1 Bob 3 2 Charlie 7 3 David 5
In [3]:
# Applying a Function to Rows
import pandas as pd
data = {
'math': [90, 80, 70, 60],
'science': [85, 75, 65, 55],
'english': [88, 78, 68, 58]
}
df = pd.DataFrame(data)
#######################################
def total_score(row):
return row['math'] + row['science'] + row['english']
#######################################
df['total_score'] = df.apply(total_score, axis=1)
print(df)
math science english total_score 0 90 85 88 263 1 80 75 78 233 2 70 65 68 203 3 60 55 58 173
In [4]:
# Using apply with Additional Arguments
import pandas as pd
data = {
'values': [1, 2, 3, 4]
}
df = pd.DataFrame(data)
######################################
def add_constant(x, constant):
return x + constant
######################################
df['values_plus_10'] = df['values'].apply(add_constant, constant=10)
print(df)
values values_plus_10 0 1 11 1 2 12 2 3 13 3 4 14
