create true or false row based on if else condition in python pandas in python

To create a true or false row based on a condition in a Pandas DataFrame, you can use the apply() method with a lambda function that checks the condition. Here's an example:

main.py
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'A': [10, 20, 30], 'B': [5, 15, 25]})

# Create a new column based on the condition
df['C'] = df.apply(lambda x: True if x['A'] > x['B'] else False, axis=1)

# Print the updated DataFrame
print(df)
266 chars
11 lines

This code creates a new column C in the DataFrame df that is True if the value in column A is greater than the value in column B, and False otherwise. The apply() method is called with a lambda function that checks this condition for each row, and the axis=1 parameter ensures that the function is applied row-wise instead of column-wise.

Output:

main.py
    A   B      C
0  10   5   True
1  20  15   True
2  30  25   True
68 chars
5 lines

related categories

gistlibby LogSnag