Search code examples
pythonpandasdataframedrop

Drop pandas rows based condition of 2 column combination


I have a pandas table with 2 columns, Month & Year.

Month   Year
1       2020
2       2020
3       2020
4       2020
5       2020
6       2020
7       2020
8       2020
9       2020
10      2020
11      2020
12      2020
1       2021
2       2021
3       2021
4       2021
5       2021

I want to drop a specific month in this example January 2020 (1/2020).

However, what I have done is to remove all rows with 1 in Month and all rows with 2020 in Year.

#Dataframe
foo = pd.DataFrame({'Month':[1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5],'Year':[2020,2020,2020,2020,2020,2020,2020,2020,2020,2020,2020,2020,2021,2021,2021,2021,2021]})

#What I have tried:
foo[(foo.Month != 1) & (foo.Year != 2020)]

#Output:
Month   Year
2       2021
3       2021
4       2021
5       2021

How do I remove a specific Month and Year combination?


Solution

  • Do "not and" instead of "not and not"

    foo[~((foo.Month == 1) & (foo.Year == 2020))]