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.
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:
Delete a row in a DataFrame based on a certain column value in Python's Pandas library
df = df[df.Age != 30]
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Alternatively, you can also use boolean indexing
Delete a row in a DataFrame based on a certain column value in Python's Pandas library using 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:
Delete a row in a DataFrame based on a certain column value in Python's Pandas library the query method
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
Delete a row in a DataFrame based on a certain column value in Python's Pandas library using the drop method
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
Delete a row in a DataFrame based on a certain column value in Python's Pandas library by passing the axis=0 argument
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.