Answers for "if else python pandas column"

3

pandas if else new column

# Method 1:
df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'
#or
df.loc[df['set_of_numbers'] <= 4, 'equal_or_lower_than_4?'] = 'True' 

# Method 2:
df['new column name'] = df['column name'].apply(lambda x: 'value if condition is met' if x condition else 'value if condition is not met')
#or
df['name_match'] = df['First_name'].apply(lambda x: 'Match' if x == 'Bill' else 'Mismatch')

# or
df.loc[(df['First_name'] == 'Bill') | (df['First_name'] == 'Emma'), 'name_match'] = 'Match'  
df.loc[(df['First_name'] != 'Bill') & (df['First_name'] != 'Emma'), 'name_match'] = 'Mismatch'
Posted by: Guest on April-13-2021
2

pandas if else

df.loc[df['column name'] condition, 'new column name'] = 'value if condition is met'
Posted by: Guest on May-10-2020
0

if else python pandas dataframe

# create a list of our conditions
conditions = [
    (df['likes_count'] <= 2),
    (df['likes_count'] > 2) & (df['likes_count'] <= 9),
    (df['likes_count'] > 9) & (df['likes_count'] <= 15),
    (df['likes_count'] > 15)
    ]

# create a list of the values we want to assign for each condition
values = ['tier_4', 'tier_3', 'tier_2', 'tier_1']

# create a new column and use np.select to assign values to it using our lists as arguments
df['tier'] = np.select(conditions, values)

# display updated DataFrame
df.head()
Posted by: Guest on October-19-2020

Python Answers by Framework

Browse Popular Code Answers by Language