Answers for "how to flag 0 or 1 if some condition is met in python dataframe"

2

pandas create a new column based on condition of two columns

conditions = [
    df['gender'].eq('male') & df['pet1'].eq(df['pet2']),
    df['gender'].eq('female') & df['pet1'].isin(['cat', 'dog'])
]

choices = [5,5]

df['points'] = np.select(conditions, choices, default=0)

print(df)
     gender      pet1      pet2  points
0      male       dog       dog       5
1      male       cat       cat       5
2      male       dog       cat       0
3    female       cat  squirrel       5
4    female       dog       dog       5
5    female  squirrel       cat       0
6  squirrel       dog       cat       0
Posted by: Guest on December-01-2020
0

add a value to an existing field in pandas dataframe after checking conditions

gapminder['gdpPercap_ind'] = gapminder.gdpPercap.apply(lambda x: 1 if x >= 1000 else 0)
gapminder.head()
Posted by: Guest on September-18-2020

Code answers related to "how to flag 0 or 1 if some condition is met in python dataframe"

Python Answers by Framework

Browse Popular Code Answers by Language