Search code examples
pythonpandasseriesdrop

Remove multiple keys from a Pandas series


I have a Pandas series and would like to remove multiple items using a list of keys to be deleted, but this list includes elements which is not a part of the Series keys.

I can do this using the commands below, but believe there must be a more elegant way to achieve this.

series1 = pd.Series({'a':8, 'b':7,'c':6, 'd':5})
list1 = ['b', 'c','e','f']

series1.drop(set(series1.keys()).intersection(set(list1)))

Result:

a    8
d    5
dtype: int64

Is there any idea?


Solution

  • We can filter with Index.difference (which performs the same set difference without all of the extraction/explicit conversion). In Pandas, inclusive masks tend to be faster and shorter than exclusive masks/dropping rows:

    series1[series1.index.difference(list1)]
    
    a    8
    d    5
    dtype: int64