Apply a function to columns of pandas
DataFrame
The apply() function can apply a given function to any row or column of a pandas DataFrame. We can apply any built-in function, user-defined functions, or even a one-liner lambda
function.
To apply a function to columns of pandas
DataFrame:
- Use the
apply()
function.
# Apply a function to columns of DataFrame in Python import pandas as pd # Create a DataFrame dt = pd.DataFrame([[15,26,33,82],[22,92,65,14]], columns = ['c1','c2','c3','c4']) # Create a function def x(a): return a + 1 # Use the apply() function to apply a function to columns of DataFrame in Python dt_new = dt.apply(x, axis = 0) print(dt_new) # Output: c1 c2 c3 c4 # 0 16 27 34 83 # 1 23 93 66 15
In the above sample code, we create a function x()
and a DataFrame. We use the apply()
function to apply this function to the columns of pandas
DataFrame.
The
axis
parameter specifies if the function is to be applied to a row or a column. We specify its value as one for rows and zero for columns.
Similarly, we can also apply a built-in function to a column of Pandas DataFrame.
See the code below.
# Apply a function to columns of DataFrame in Python import pandas as pd # Create a DataFrame dt = pd.DataFrame([[15,26,33,82],[22,92,65,14]], columns = ['c1','c2','c3','c4']) # Use the apply() function to apply a function to columns of DataFrame in Python dt_new = dt[["c1","c2"]].apply(sum, axis = 0) print(dt_new) # Output: c1 37 # c2 118
In the above sample code, we apply the sum()
function to two columns of a DataFrame.
To conclude.
This particular article demonstrates how to apply a function to columns of pandas
DataFrame in Python using the apply()
function.
Explore more from this category at Python DataFrame. Alternatively, search and view other topics at All Tutorials.