The following tutorial demonstrates how to apply a function with arguments on a pandas DataFrame. Example:
Pandas apply()
The DataFrame apply() function allows you to quickly and easily apply operations or transformations to a given DataFrame on a row-by-row or column-by-column basis.
When using the apply() method with arguments, you can specify the axis that should be used for iteration (i.e., rows or columns). This is done by passing in either 0 (for rows) or 1 (for columns) as the first argument. For example, if you want to apply an operation across all the columns of a DataFrame, you could use the following syntax:
DataFrame.apply(operation, axis=1)
Here a simple example of how to apply a function to a dataframe without arguments
import pandas as pd
def myFunction(x):
return 2 * x + 1
df = pd.DataFrame({'Col1': [3, 7], 'Col2': [1, 2]})
print(df)
returns
Col1 Col2
0 3 1
1 7 2
Then if we apply the function called "myFunction"
df_new = df.apply(myFunction, axis=1)
print(df_new)
we will get:
Col1 Col2
0 7 3
1 15 5
Apply a function with arguments
In addition, it has the ability to accept arguments, making it even more flexible and useful for a variety of tasks.
Using positional arguments
def myFunction_02(x, a, b):
return a * x + b
df_new = df.apply(myFunction_02, a=2, b=1)
print(df_new)
Output
Col1 Col2
0 7 3
1 15 5
Another example: Applying the function for a given column:
df_new = df.copy()
df_new['Col2'] = df['Col2'].apply(myFunction_02, a=2, b=1)
print(df_new)
Output
Col1 Col2
0 3 3
1 7 5
Other approach:
def myFunction_02(x, a, b, c):
return a * x[c] + b
df_new = df.apply(myFunction_02, a=2, b=1, c='Col2', axis=1)
print(df_new)
Output
0 3
1 5
dtype: int64
Using keyword arguments
def myFunction_03(x, a, b):
return a * x + b
df_new = df.apply(myFunction_03, args=(2, 1))
print(df_new)
Output
Col1 Col2
0 7 3
1 15 5
Using positional and keyword arguments
def myFunction_04(x, a, b, c):
return a * x + b - c
df_new = df.apply(myFunction_04, args=(2, 1), c=100)
print(df_new)
Output
Col1 Col2
0 -93 -97
1 -85 -95
References
Links | Site |
---|---|
apply() | pandas.pydata.org |