Apply a function to single or selected columns or rows in Pandas Dataframe - GeeksforGeeks

03 Jul, 2020
In this article, we will learn different ways to apply a function to single or selected columns or rows in Dataframe. We will use Dataframe/series.apply() method to apply a function.
Syntax: Dataframe/series.apply(func, convert_dtype=True, args=())
Parameters: This method will take following parameters :func: It takes a function and applies it to all values of pandas series.convert_dtype: Convert dtype as per the function’s operation.args=(): Additional arguments to pass to function instead of series.
Return Type: Pandas Series after applied function/operation.
Method 1: Using Dataframe.apply() and lambda function.Example 1: For Column
# import pandas and numpy libraryimport pandas as pdimport numpy as np  # List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'),                   index = list('abc'))  # Apply function numpy.square() to lambda# to find the squares of the values of # column whose column name is 'z'new_df = df.apply(lambda x: np.square(x) if x.name == 'z' else x)  # Outputnew_df
Output :
Example 2: For Row.
# import pandas and numpy libraryimport pandas as pdimport numpy as np# List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'),                    index = list('abc'))  # Apply function numpy.square() to lambda # to find the squares of the values of row# whose row index is 'b'new_df = df.apply(lambda x: np.square(x) if x.name == 'b' else x,                 axis = 1)  # Outputnew_df
Output :
Method 2: Using Dataframe/series.apply() & [ ] Operator.
Example 1: For Column.
# import pandas and numpy libraryimport pandas as pdimport numpy as np  # List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'),                    index = list('abc'))  # Apply a function to one column 'z'# and assign it back to the same column df['z'] = df['z'].apply(np.square)  # Outputdf
Output :
Example 2: For Row.
# import pandas and numpy libraryimport pandas as pdimport numpy as np  # List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'),                   index = list('abc'))  # Apply a function to one row 'b' # and assign it back to the same row df.loc['b'] = df.loc['b'].apply(np.square)  # Outputdf
Output :
Method 3: Using numpy.square() method and [ ] operator.Example 1: For Column
# import pandas and numpy libraryimport pandas as pdimport numpy as np  # List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'),                   index = list('abc'))  # Apply a function to one column 'z' and # assign it back to the same column df['z'] = np.square(df['z'])  # Outputprint(df)
Output :
Example 2: For Row.
# import pandas and numpy libraryimport pandas as pdimport numpy as np  # List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'), index = list('abc'))  # Apply a function to one row 'b' and # assign it back to the same rowdf.loc['b'] = np.square(df.loc['b'])  # Outputdf
Output :
We can also apply a function to more than one column or row in the dataframe.
Example 1: For Column
# import pandas and numpy libraryimport pandas as pdimport numpy as np  # List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'),                   index = list('abc'))  # Apply function numpy.square() # for square the values of# two columns 'x' and 'y' new_df = df.apply(lambda x: np.square(x) if x.name in ['x', 'y'] else x)  # Outputnew_df
Output :
Example 2: For Row.
# import pandas and numpy libraryimport pandas as pdimport numpy as np  # List of Tuplesmatrix = [(1, 2, 3),          (4, 5, 6),          (7, 8, 9)         ]  # Create a DataFrame objectdf = pd.DataFrame(matrix, columns = list('xyz'),                  index = list('abc'))  # Apply function numpy.square() to # square the values of two rows # 'b' and 'c'new_df = df.apply(lambda x: np.square(x) if x.name in ['b', 'c'] else x,                 axis = 1)  # Outputnew_df
Output :
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python