Skip to content Skip to sidebar Skip to footer

Checking A Data Frame Column For Membership Of A List And Appending A Result?

Working with a Pandas DataFrame, df, and a function as follows def code(x): for item in x: if x in [21,32]: return'Cat A' elif x in [22,34]:

Solution 1:

Using .loc conditions

This solution is quite straightforward, each row will assign a value based on the condition in the .loc(). The last row uses .fillna() to assign a default value.

df.loc[df['your_column'].isin([21,32]), 'Category'] = 'CAT A'
df.loc[df['your_column'].isin([22,34]), 'Category'] = 'CAT B'
df['Category'] = df.Category.fillna('Sorry') 

Using np.select

This is the method described in this answer suggested by @ALollz. It is probably the best way to proceed, but it's somewhat burdensome for simple cases.

First you need to list your conditions and choices, then, using np.selectyou can attribute a 'Category' value based on the given conditions. The default parameter will be used to fill where all conditions have failed.

conditions = [df['your_column'].isin([21,32]), df['your_column'].isin([22,34])]
choices = ['CAT A', 'CAT B']
df['Category'] = np.select(conditions, choices, default="Sorry")

Post a Comment for "Checking A Data Frame Column For Membership Of A List And Appending A Result?"