6

I have a data frame df1 and list x:

In [22] : import pandas as pd
In [23]: df1 = pd.DataFrame({'C': range(5), "B":range(10,20,2), "A":list('abcde')})
In [24]: df1
Out[24]:
   A   B  C
0  a  10  0
1  b  12  1
2  c  14  2
3  d  16  3
4  e  18  4

In [25]: x = ["b","c","g","h","j"]

What I want to do is to select rows in data frame based on the list. Returning

   A   B  C
1  b  12  1
2  c  14  2

What's the way to do it? I tried this but failed.

df1.join(pd.DataFrame(x),how="inner")

2 Answers 2

11

Use isin to return a boolean index for you to index into your df:

In [152]:

df1[df1['A'].isin(x)]
Out[152]:
   A   B  C
1  b  12  1
2  c  14  2

This is what isin is returning:

In [153]:

df1['A'].isin(x)
Out[153]:
0    False
1     True
2     True
3    False
4    False
Name: A, dtype: bool
0

Use df[df["column"].isin(values)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.