Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Python Pandas - Filtering few rows from a DataFrame on the basis of sum
To filter few rows from DataFrame on the basis of sum, we have considered an example with Student Marks. We need to calculate the sum of a particular subject wherein the total is more than 200 i.e. the total of all 3 students in that particular subject is more than 200. In this way we can fiter our rows with total less than 200.
At first, let us create a DataFrame with 3 columns i.e. records of 3 students −
dataFrame = pd.DataFrame({'Jacob_Marks': [95, 90, 70, 85, 88],'Ted_Marks': [60, 50, 65, 85, 70],'Jamie_Marks': [77, 76, 60, 45, 50]})
Filtering on the basis of rows. Fetching rows with total greater than 200 for all the 3 students −
dataFrame = dataFrame[dataFrame.sum(axis=1) > 200]
Example
Following is the complete code −
import pandas as pd
# create a dataframe with 3 columns
dataFrame = pd.DataFrame({'Jacob_Marks': [95, 90, 70, 85, 88],'Ted_Marks': [60, 50, 65, 85, 70],'Jamie_Marks': [77, 76, 60, 45, 50]})
print"Dataframe...\n",dataFrame
# filtering on the basis of rows
# fetching rows with total greater than 200 for all the 3 students
dataFrame = dataFrame[dataFrame.sum(axis=1) > 200]
# dataframe
print"Updated Dataframe...\n",dataFrame
Output
This will produce the following output −
Dataframe... Jacob_Marks Jamie_Marks Ted_Marks 0 95 77 60 1 90 76 50 2 70 60 65 3 85 45 85 4 88 50 70 Updated Dataframe... Jacob_Marks Jamie_Marks Ted_Marks 0 95 77 60 1 90 76 50 3 85 45 85 4 88 50 70
Advertisements
