How delete rows from dataframe after comparison

Viewed 48

I want to filter my dataframe, use the part of filter with condition. And I do't know how to do it

import numpy as np


table = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],
                  'rating': [3., 4., 5., np.nan, np.nan, np.nan],
                  'name': ['John', 'Paul', 'Adam', 'Graham', 'Eva', 'Thomas']})

filter = pd.DataFrame({'name': ['John', 'Paul','Adam', 'Graham', 'Eva', 'Thomas'],
                       'qty': [1, 1, 3, 10, 7, 5]})

>>> table 
  movie    name  rating
0   thg    John       3
1   thg    Paul       4
3   mol    Adam       5
4   mol  Graham     NaN
5   lob     Eva     NaN
6   lob  Thomas     NaN

I know that this doesn't work, but I can't change this, help me please

result=df[(df['name'] == filter[qty<3]) ]


>>> result 
  movie    name  rating
0   thg    John       3
1   thg    Paul       4
4 Answers

I believe you need:

table[table['name'].isin(filt.loc[filt['qty']<3,'name'])]

  movie  rating  name
0   thg     3.0  John
1   thg     4.0  Paul

Note: i have changed the filter variable to filt since filter is a builtin function and you should not name a variable with such name

You can try with. I am undeleting this answer because of not using loc unlike the other answers, although it is essentially the same:

result = table[table['name'].isin(filter[filter['qty']<3]['name'].values)]

Use Series.isin with callable :

table[table['name'].isin(df_filter.loc[lambda x: x['qty']<3, 'name'])]


  movie  rating  name
0   thg     3.0  John
1   thg     4.0  Paul

or DataFrame.merge

table.merge(df_filter.loc[lambda x: x['qty'].lt(3), ['name']])

I have a more concise solution, why not use query:

df=table.merge(filter,on="name")
df.query("qty<3")

Related