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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With