conditions pandas code example

Example 1: conditions in pandas dataframe

from pandas import DataFrame
  
names = {'First_name': ['Hanah', 'Ria', 'Jay', 'Bholu', 'Sachin']}
df = DataFrame(names, columns =['First_name'])
  
df['Status'] = df['First_name'].apply(lambda x: 'Found' if x == 'Ria' else 'Not Found')
  
print (df)

Example 2: new dataframe based on certain row conditions

# Create variable with TRUE if nationality is USA
american = df['nationality'] == "USA"

# Create variable with TRUE if age is greater than 50
elderly = df['age'] > 50

# Select all cases where nationality is USA and age is greater than 50
df[american & elderly]

Example 3: conditions in pandas dataframe

df.loc[df[‘column name’] condition, ‘new column name’] = ‘value if condition is met’