You have a pandas dataframe and you want to delete rows from this dataframe which meet certain conditions.
import pandas as pd url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/clothing_store_sales.csv" df = pd.read_csv(url) df = df.head()
1 . Delete rows based on single condition –
Let’s say that you want to delete all the rows where Method of Payment is Proprietary card. The easiest way to delete all these rows is to select all rows where the Method of Payment is not Proprietary card.
df1 = df[df['Method of Payment'] != 'Proprietary Card']
2 . Delete rows based on Multiple Conditions –
You can also delete rows based on multiple conditions.
Let’s say I want to delete all the rows where the Gender is Female and the age is greater than 30.
df2 = df[~((df['Gender']=='Female') & (df['Age'] > 30))]
Here, I first selected all the rows that meet those conditions and then used tilda (~) to negate the result to select all the rows that don’t satisfied those conditions.
Related Posts –
1 . Pandas – Delete one or more columns from a dataframe.