Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep rows of a dataframe that are present in a list

I have a list of unique elements, and also a dataframe, having a number of columns. I wish to keep all the rows in the dataframe that also is present in the list.

For example consider having a list and a dataframe/csv file

List: [a, c, e]

DataFrame:

ColA    ColB
  a       1
  b       2
  c       3
  d       4
  e       5
  f       6

I wish to modify the dataframe to:

ColA    ColB
  a       1
  c       3
  e       5

How can I do this ? The values in ColA using which I wish to keep and remove elements are all unique.

like image 751
Tavish Jain Avatar asked Oct 30 '25 22:10

Tavish Jain


1 Answers

Use Series.isin:

In [2597]: df
Out[2597]: 
  ColA  ColB
0    a     1
1    b     2
2    c     3
3    d     4
4    e     5
5    f     6

In [2599]: l = ['a', 'c', 'e']

In [2602]: df = df[df['ColA'].isin(l)]

In [2603]: df
Out[2603]: 
  ColA  ColB
0    a     1
2    c     3
4    e     5
like image 181
Mayank Porwal Avatar answered Nov 02 '25 13:11

Mayank Porwal