What is Pandas apply() method
The apply() method can be applied both to series and Dataframes where a function can be applied to both series and individual elements based on the type of function provided.
Syntax: s.apply(func, convert_dtype=True, args=())
Pandas DataFrame apply() Method
This method can be used on both a pandas Dataframe and series. The function passed as an argument typically works on rows/columns. The code below illustrates how apply() method works on Pandas Dataframe.
Python3
# Importing pandas library with an alias pd import pandas as pd # Dataframe generation gfg_string = 'w3wiki' gfg_list = 5 * [pd.Series( list (gfg_string))] gfg_df = pd.DataFrame(data = gfg_list) print ( "Original dataframe:\n" + \ gfg_df.to_string(index = False , header = False ), end = '\n\n' ) # Using apply method for sorting # rows of characters present in # the original dataframe new_gfg_df = gfg_df. apply ( lambda x:x.sort_values(), axis = 1 ) print ( "Transformed dataframe:\n" + \ new_gfg_df.to_string(index = False , header = False ), end = '\n\n' ) |
Output:
Pandas Series apply() Method
The below Code illustrates how to apply() method to the Pandas series:
Python3
# Importing pandas library with an alias pd import pandas as pd # Series generation gfg_string = 'w3wiki' gfg_series = pd.Series( list (gfg_string)) print ( "Original series\n" + gfg_series.to_string(index = False , header = False ), end = '\n\n' ) # Using apply method for converting characters # present in the original series new_gfg_series = gfg_series. apply ( str .upper) print ( "Transformed series:\n" + new_gfg_series.to_string(index = False , header = False ), end = '\n\n' ) |
Output: