Home » Pandas: How to Apply Function to Every Row in DataFrame

Pandas: How to Apply Function to Every Row in DataFrame

by Erma Khan

You can use the following basic syntax to apply a function to every row in a pandas DataFrame:

df['new_col'] = df.apply(lambda x: some function, axis=1)

This syntax applies a function to each row in a pandas DataFrame and returns the results in a new column.

The following example shows how to use this syntax in practice.

Example: Apply Function to Every Row in DataFrame

Suppose we have the following pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'A': [5, 4, 7, 9, 12, 9, 9, 4],
                   'B': [10, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print(df)

    A   B
0   5  10
1   4   8
2   7  10
3   9   6
4  12   6
5   9   5
6   9   9
7   4  12

Now suppose we would like to apply a function that multiplies the values in column A and column B and then divides by 2.

We can use the following syntax to apply this function to each row in the DataFrame:

#create new column by applying function to each row in DataFrame
df['z'] = df.apply(lambda x: x['A'] * x['B'] / 2, axis=1)

#view updated DataFrame
print(df)

    A   B     z
0   5  10  25.0
1   4   8  16.0
2   7  10  35.0
3   9   6  27.0
4  12   6  36.0
5   9   5  22.5
6   9   9  40.5
7   4  12  24.0

Column z displays the results of the function.

For example:

  • First row: A * B / 2 = 5 * 10 / 2 = 25
  • Second row: A * B / 2 = 4 * 8 / 2 = 16
  • Third row: A * B / 2 = 7 * 10 / 2 = 35

And so on.

You can use similar syntax with lambda to apply any function you’d like to every row in a pandas DataFrame.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Apply Function to Pandas Groupby
How to Perform a GroupBy Sum in Pandas
How to Use Groupby and Plot in Pandas

Related Posts