1

There is a pandas dataframe:

  df = pd.DataFrame({'c1':['a','b','c','d'],'c2':[1,2,3,4]})

c1  c2
0   a   1
1   b   2
2   c   3
3   d   4

And a pandas Series:

list1 = pd.Series(['b','c','e','f'])

Out[6]:
0    a
1    b
2    c
3    e

How to create a new data frame that contains rows where c1 is in list1.

output:

c1  c2
0   b   2
1   c   3 
0

4 Answers 4

4

You can use df.isin:

In [582]: df[df.c1.isin(list1)]
Out[582]: 
  c1  c2
1  b   2
2  c   3

Or, using df.loc, if you want to modify your slice:

In [584]: df.loc[df.c1.isin(list1), :]
Out[584]: 
  c1  c2
1  b   2
2  c   3
Sign up to request clarification or add additional context in comments.

Comments

3

Using query

In [1133]: df.query('c1 in @list1')
Out[1133]:
  c1  c2
1  b   2
2  c   3

Or, using isin

In [1134]: df[df.c1.isin(list1)]
Out[1134]:
  c1  c2
1  b   2
2  c   3

Comments

2

Both @JohnGalt's and @COLDSPEED's answers are more idiomatic pandas. Please don't use these answers. They are intended to be fun and illustrative of other parts of the pandas and numpy api.

Alt 1
This is utilizing numpy.in1d which acts as a proxy for pd.Series.isin

df[np.in1d(df.c1.values, list1.values)]

  c1  c2
1  b   2
2  c   3

Alt 2
Use set logic

df[df.c1.apply(set) & set(list1)]

  c1  c2
1  b   2
2  c   3

Alt 3
Use pd.Series.str.match

df[df.c1.str.match('|'.join(list1))]

  c1  c2
1  b   2
2  c   3

3 Comments

now it's getting really challenging to find yet another way to do that... ;)
Better +1 before that pandas guy comes and trashes you for using numpy :^)
@cᴏʟᴅsᴘᴇᴇᴅ we're good (-: I do right by everyone by calling it out.
0

For the sake of completenes

yet another way (definitely not the best one) to achieve that:

In [4]: df.merge(list1.to_frame(name='c1'))
Out[4]:
  c1  c2
0  b   2
1  c   3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.