Deleting DataFrame row in Pandas based on column value
In Pandas, you can delete a row in a DataFrame based on a certain column value by using the drop()
method and passing the index label of the row you want to delete. For example, if you have a DataFrame named df
and you want to delete a row where the value in the 'Age' column is 30, you can use the following code:
df = df[df.Age != 30]
Alternatively, you can also use boolean indexing
df = df[df['Age'] != 30]
Both of the above lines of code will create a new DataFrame that doesn't include the rows where the 'Age' column is equal to 30.
Another way is to use the DataFrame.query() method. Here's an example:
df = df.query('Age != 30')
This method creates a copy of the original dataframe with the query passed as a string
Another way to remove the rows with certain value based on column is using drop() method with boolean indexing
df.drop(df[df['Age'] == 30].index, inplace=True)
You can also pass axis=0 while calling drop method and condition in the same line
df = df.drop(df[df['Age'] == 30].index, axis=0)
inplace=True
will make the changes to the existing DataFrame, if you don't pass it, it will return a copy of the DataFrame with the changes.