create a label based on a condition in dataframe pandas in python

You can create a new label in a column based on a condition in a pandas DataFrame using the loc method as shown below:

main.py
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'score': [68, 72, 85, 91, 77, 83], 'passing_status': ['']*6})

# Create a function to determine passing status
def passing_status(score):
    if score >= 80:
        return 'Pass'
    else:
        return 'Fail'

# Apply the function to create the new label
df.loc[:, 'passing_status'] = df['score'].apply(passing_status)

# Display the DataFrame
print(df)
425 chars
18 lines

This will create a new column called 'passing_status' in your DataFrame. The values in this column will be determined by applying a condition to the 'score' column. In this example, any score that is 80 or above will be labeled as 'Pass' and any score below 80 will be labeled as 'Fail'. You can modify the passing_status function to create labels based on different conditions.

related categories

gistlibby LogSnag