📜  pandas lambda if else - Python (1)

📅  最后修改于: 2023-12-03 15:18:13.969000             🧑  作者: Mango

Pandas Lambda If-Else - Python

In Pandas, we often need to conditionally apply a function (similar to an if-else statement). We can do this using the apply method along with a lambda function. In this tutorial, we will see how to use Pandas Lambda If-Else with an example.

Example

Suppose we have a DataFrame df with two columns A and B. We want to create a new column C based on the values of columns A and B.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]})
Basic If-Else

Let's create a new column C such that if the value in column A is greater than 2, then C is equal to the value in column B, otherwise C is equal to the value in column A.

df['C'] = df.apply(lambda x: x['B'] if x['A'] > 2 else x['A'], axis=1)

The above code uses a lambda function that checks the value in column A for each row. If the value is greater than 2, the function returns the value in column B, otherwise it returns the value in column A.

Multiple Conditions

We can also use multiple conditions in our lambda function.

Let's create a new column C such that if the value in column A is greater than 2 and the value in column B is even, then C is equal to the value in column B, otherwise C is equal to the value in column A.

df['C'] = df.apply(lambda x: x['B'] if x['A'] > 2 and x['B'] % 2 == 0 else x['A'], axis=1)

The above code checks if the value in column A is greater than 2 and the value in column B is even. If both conditions are true, the function returns the value in column B, otherwise it returns the value in column A.

Numpy Where

We can also achieve the same functionality using numpy where function.

Let's create a new column C using numpy where function such that if the value in column A is greater than 2 and the value in column B is even, then C is equal to the value in column B, otherwise C is equal to the value in column A.

df['C'] = np.where((df['A'] > 2) & (df['B'] % 2 == 0), df['B'], df['A'])

The above code creates a new column C using numpy where function. It checks if the value in column A is greater than 2 and the value in column B is even. If both conditions are true, C is equal to the value in column B, otherwise it is equal to the value in column A.

Conclusion

In this tutorial, we saw how to use Pandas Lambda If-Else to conditionally apply a function to a DataFrame. We also saw how to use multiple conditions and numpy where function for the same. Pandas Lambda If-Else is a powerful tool for data manipulation and is frequently used in data analysis tasks.