make a condition statement on column pandas
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
make a condition statement on column pandas
df['color'] = ['red' if x == 'Z' else 'green' for x in df['Set']]
add a value to an existing field in pandas dataframe after checking conditions
# Create a new column called based on the value of another column
# np.where assigns True if gapminder.lifeExp>=50
gapminder['lifeExp_ind'] = np.where(gapminder.lifeExp >= 50, True, False)
gapminder.head(n=3)
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
python conditionally create new column in pandas dataframe
# If you only have one condition use numpy.where()
# Example usage with np.where:
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')}) # Define df
print(df)
Type Set
0 A Z
1 B Z
2 B X
3 C Y
# Add new column based on single condition:
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)
Type Set color
0 A Z green
1 B Z green
2 B X red
3 C Y red
# If you have multiple conditions use numpy.select()
# Example usage with np.select:
df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')}) # Define df
print(df)
Type Set
0 A Z
1 B Z
2 B X
3 C Y
# Set the conditions for determining values in new column:
conditions = [
(df['Set'] == 'Z') & (df['Type'] == 'A'),
(df['Set'] == 'Z') & (df['Type'] == 'B'),
(df['Type'] == 'B')]
# Set the new column values in order of the conditions they should
# correspond to:
choices = ['yellow', 'blue', 'purple']
# Add new column based on conditions and choices:
df['color'] = np.select(conditions, choices, default='black')
print(df)
# Returns:
Set Type color
0 Z A yellow
1 Z B blue
2 X B purple
3 Y C black
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us