Pandas Query Rows By List
I have a pandas data frame and want to return the rows from the data frame corresponding to the customer ids that appear in a list of target ids. For example, if my data frame look
Solution 1:
I guess you are looking for isin()
:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame({'customer_id':range(5), 'A':('a', 'b', 'c', 'd', 'e')})
In [3]: df
Out[3]:
A customer_id
0 a 0
1 b 1
2 c 2
3 d 3
4 e 4
In [4]: df[df.customer_id.isin((1,3))]
Out[4]:
A customer_id
1 b 1
3 d 3
[edit] To match a given target list, just use it as argument for the isin()
method:
In [5]: mylist = (1,3)
In [6]: df[df.customer_id.isin(mylist)]
Out[6]:
A customer_id
1 abcde 13 abcde 3
Post a Comment for "Pandas Query Rows By List"