Mario Aguilar
Mario Aguilar

Reputation: 29

How to systematically drop a Pandas row given a particular condition in a column?

I have a simple dataframe consisting of 3 columns: Year, Period (Month) and Inflation I want to remove even months (e.g., February, April, etc.) and the code I came up with is the following:

i = df[((df["Periodo"] == "Febrero") | (df["Periodo"] == "Abril") | (df["Periodo"] =="Junio") | (df["Periodo"] =="Agosto") | (df["Periodo"] =="Octubre") | (df["Periodo"] =="Diciembre"))].index
df.drop(i, inplace = True)

Is there a quicker way rather than typing those tedious OR conditions to make the index? Like a for loop or something. Thanks

Upvotes: 0

Views: 30

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use .isin() (note the ~ used as negation):

to_drop = ["Febrero", "Abril", "Junio", "Agosto", "Octubre", "Diciembre"]
print(df[~df.Periodo.isin(to_drop)])

Upvotes: 2

Related Questions