Eliminate rows with condition in pandas DataFrame in Python
This tutorial will teach us how to eliminate rows with conditions in Pandas DataFrame in Python.
So to delete/eliminate rows with conditions we first need to define a table with some data and for that, we need to import pandas.
import pandas as pd
Now that we have pandas imported, We are ready to define a table and use it.
We will define the table using DataFrame in pandas:
table = pd.DataFrame( { 'name' : ['Maxx', 'May', 'Ron', 'Eliza'], 'Age' : [25,27,22,31], 'Department' : ['sales', 'marketing', 'marketing', 'sales'], 'gender' : ['female', 'female', 'male', 'female'] } ) print(table)
In dataframe, when a table is defined it looks like a dictionary with key-value pairs, When we print the table it looks something like this:
Output:
name Age Department gender 0 Maxx 25 sales female 1 May 27 marketing female 2 Ron 22 marketing male 3 Eliza 31 sales female
Eliminate row with condition
Now that we have a table, We see how to delete a row with some particular condition.
- If we want to delete rows with an age greater than 25, we can do that by:
table.drop(table[(table['Age'] > 25)].index , inplace=True) print(table)
Output:
name Age Department gender 0 Maxx 25 sales female 2 Ron 22 marketing male
Eliminate rows with multiple conditions
This will help us eliminate rows with the specified conditions:
table.drop(table[ (table['Department'] == 'sales') | (table['Age'] > 25) ].index , inplace=True) print(table)
Output:
name Age Department gender 2 Ron 22 marketing male
Leave a Reply