Filter pandas data frame by id list

I have a pandas dataframe that has a list of user identifiers 'subscriber_id' and other information.

I want to select only subscribers not on this list A.

So, if our data frame contains information for subscribers [1,2,3,4,5], and my list of exceptions is [2,4,5], now I should get an information frame with information for [1,3]

I tried using the mask as follows:

temp = df.mask(lambda x: x['subscriber_id'] not in subscribers)

but no luck!

I am sure it not inis a valid Python syntax since I tested it on a list like this:

c = [1,2,3,4,5]
if 5 not in c:
    print 'YAY'
>> YAY

Any suggestion or alternative way to filter a data frame?

+4
source share
1

isin:

In [30]: df = pd.DataFrame({'subscriber_id':[1,2,3,4,5]})

In [31]: df
Out[31]: 
   subscriber_id
0              1
1              2
2              3
3              4
4              5

[5 rows x 1 columns]

In [32]: mask = df['subscriber_id'].isin([2,4,5])

In [33]: mask
Out[33]: 
0    False
1     True
2    False
3     True
4     True
Name: subscriber_id, dtype: bool

In [34]: df.loc[~mask]
Out[34]: 
   subscriber_id
0              1
2              3

[2 rows x 1 columns]

df.mask, NDFrame . lambda x: x['subscriber_id'] not in subscribers - , .

df.mask, isin :

In [43]: df['subscriber_id'].mask(df['subscriber_id'].isin([2,4,5]).values)
Out[43]: 
0     1
1   NaN
2     3
3   NaN
4   NaN
Name: subscriber_id, dtype: float64
+8

Source: https://habr.com/ru/post/1541167/


All Articles