Pandas provides a rich collection of functions to perform data analysis in Python. While performing data analysis, quite often we require to filter the data to remove unnecessary rows or columns.
We have already discussed earlier how to drop rows or columns based on their labels. However, in this post we are going to discuss several approaches on how to drop rows from the dataframe based on certain condition applied on a column. Retain all those rows for which the applied condition on the given column evaluates to
To download the CSV used in code, click here.
You are given the “nba.csv” dataset. Drop all the players from the dataset whose age is below 25 years.
Solution #1 : We will use vectorization to filter out such rows from the dataset which satisfy the applied condition.
In this dataframe, currently, we are having 458 rows and 9 columns. Let’s use vectorization operation to filter out all those rows which satisfy the given condition.
As we can see in the output, the returned dataframe only contains those players whose age is greater than or equal to 25 years.
Solution #2 : We can use the
DataFrame.drop() function to drop such rows which does not satisfy the given condition.
As we can see in the output, we have successfully dropped all those rows which do not satisfy the given condition applied to the ‘Age’ column.
- Python | Creating a Pandas dataframe column based on a given condition
- Python | Delete rows/columns from DataFrame using Pandas.drop()
- Selecting rows in pandas DataFrame based on conditions
- Return the Index label if some condition is satisfied over a column in Pandas Dataframe
- Create a new column in Pandas DataFrame based on the existing columns
- How to drop one or multiple columns in Pandas Dataframe
- Ranking Rows of Pandas DataFrame
- How to iterate over rows in Pandas Dataframe
- Get all rows in a Pandas DataFrame containing given substring
- Sorting rows in pandas DataFrame
- Different ways to iterate over rows in Pandas Dataframe
- Iterating over rows and columns in Pandas DataFrame
- How to get rows/index names in Pandas dataframe
- Create a list from rows in Pandas dataframe
- Dealing with Rows and Columns in Pandas DataFrame
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.