Home > Software design >  How to filter by a list of integers?
How to filter by a list of integers?

Time:06-09

I'm in charge of payroll and they want me to give an extra bonus to our employees which ID numbers are storaged in a list.

The 'ID' column only contains integers. I know if I use str.contains I get an error, but what can I do? I need something similar to str.contains but with int

bonus = [ 1513 , 5454 , 6545 , 3425 , 32424, 2341 ,3424 ,4568, 4812]
employees = (df['ID'].str.contains(bonus)) & ((df['SALARY'] < 5000))

#I get this error (Which makes sense):
AttributeError: Can only use .str accessor with string values! 

I want an out put something like:

ID     SALARY
1513   2933
3424   2500
3425   1542
2341   3600

This is just a sample the list WAY larger

CodePudding user response:

Your issue is that the str.contains function is intended to be used to check if a string value contains a given substring. What you want to use is isin:

(df['ID'].isin(bonus))

Combining this together with your other requirement, we need to query on a given column, so we'll a call to loc:

employees = df.isin({'ID': bonus}).loc[df['SALARY'] < 5000]

CodePudding user response:

You can try this to get the result in dataframe.

df.loc[df["ID"].isin(bonus)].loc[df["SALARY"] < 5000]
  • Related