Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
Count number of rows and columns in Pandas dataframe
Next article icon

Pandas filter a dataframe by the sum of rows or columns

Last Updated : 16 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to filter a Pandas DataFrame by the sum of rows or columns. This can be useful in some conditions. Let's suppose you have a data frame consisting of customers and their purchased fruits.  The rows consist of different customers and columns contain different types of fruits. You want to filter the data frame on the basis of their purchasing. To know more about filter Pandas DataFrame by column values and rows based on conditions refer to the article links. Pandas dataframe.sum() function has been used to return the sum of the values.

Steps needed:

  1. Create or import the data frame
  2. Sum the rows: This can be done using the .sum() function and passing the parameter axis=1
  3. Sum the columns: By using the .sum() function and passing the parameter axis=0
  4. Filtering on the basis of required conditions

Filtering on basis of the sum of both rows and columns

If you want to remove the customers which did not buy any fruit or any particular fruit which was not bought by any customer. In this case, we need to filter on basis of both the values of the sum of rows or columns. Below is the code implementation of the above-proposed approach.

Python3
# importing pandas library import pandas as pd  # creating dataframe df = pd.DataFrame({'Apple': [1, 1, 0, 0, 0, 0],                    'Orange': [0, 1, 1, 0, 0, 1],                    'Grapes': [1, 1, 0, 0, 1, 1],                    'Peach': [1, 1, 0, 0, 1, 1],                    'Watermelon': [0, 0, 0, 0, 0, 0],                    'Guava': [1, 0, 0, 0, 0, 0],                    'Mango': [1, 0, 1, 0, 1, 0],                    'Kiwi': [0, 0, 0, 0, 0, 0]})  print("Dataframe before filtering\n") print(df)  # filtering on the basis of rows df = df[df.sum(axis=1) > 0]  # filtering on the basis of columns df = df.loc[:, df.sum(axis=0) > 0]  print("\nDataframe after filtering\n") print(df) 

Output:

Filtering rows on basis of the sum of few columns

Now if we want to filter those customers who did not buy either of the fruits from a limited list, for example, customers who did not buy either grape, guava, or peach should be removed from the data frame. Here, we filter the rows on the basis of certain columns which are grape, peach, and guava in this case.

On calculating the sum of all rows for these three columns, we find the sum to be zero for indexes 2 and 3.

Python3
# importing pandas library import pandas as pd  # creating dataframe df = pd.DataFrame({'Apple': [1, 1, 0, 0, 0, 0],                    'Orange': [0, 1, 1, 0, 0, 1],                    'Grapes': [1, 1, 0, 0, 1, 1],                    'Peach': [1, 1, 0, 0, 1, 1],                    'Watermelon': [0, 0, 0, 0, 0, 0],                    'Guava': [1, 0, 0, 0, 0, 0],                    'Mango': [1, 0, 1, 0, 1, 0],                    'Kiwi': [0, 0, 0, 0, 0, 0]})  print("Dataframe before filtering\n") print(df)  # list of columns to be considered columns = ['Grapes', 'Guava', 'Peach']  # filtering rows on basis of certain columns df = df[df[columns].sum(axis=1) > 0]  print("\nDataframe after filtering\n") print(df) 

Output:

Filtering few columns from the entire dataset on the basis of their sum

If you want to remove any of the columns from a list of columns that has sum equals to zero. We only sum those columns and apply the condition on them. 

Python3
# importing pandas library import pandas as pd  # creating dataframe df = pd.DataFrame({'Apple': [1, 1, 0, 0, 0, 0],                    'Orange': [0, 1, 1, 0, 0, 1],                    'Grapes': [1, 1, 0, 0, 1, 1],                    'Peach': [1, 1, 0, 0, 1, 1],                    'Watermelon': [0, 0, 0, 0, 0, 0],                    'Guava': [1, 0, 0, 0, 0, 0],                    'Mango': [1, 0, 1, 0, 1, 0],                    'Kiwi': [0, 0, 0, 0, 0, 0]})  print("Dataframe before filtering\n") print(df)  # list of columns to be considered columns = ['Apple', 'Mango', 'Guava', 'Watermelon']  # iterating through the columns and dropping # columns with sum less than equals to 0 for column in columns:     if (df[column].sum() <= 0):         df.drop(column, inplace=True, axis=1)  print("\nDataframe after filtering\n") print(df) 

Output:

In this way, we can modify our data frame in Pandas according to some situations by applying some conditions on rows and columns.


Next Article
Count number of rows and columns in Pandas dataframe
author
d2anubis
Improve
Article Tags :
  • Python
  • Python-pandas
  • Python pandas-dataFrame
  • Python Pandas-exercise
Practice Tags :
  • python

Similar Reads

  • Filter Pandas Dataframe by Column Value
    Filtering a Pandas DataFrame by column values is a common and essential task in data analysis. It allows to extract specific rows based on conditions applied to one or more columns, making it easier to work with relevant subsets of data. Let's start with a quick example to illustrate the concept: [G
    7 min read
  • Count the number of rows and columns of Pandas dataframe
    In this article, we'll see how we can get the count of the total number of rows and columns in a Pandas DataFrame. There are different methods by which we can do this. Let's see all these methods with the help of examples. Example 1: We can use the dataframe.shape to get the count of rows and column
    2 min read
  • Sort the Pandas DataFrame by two or more columns
    In this article, our basic task is to sort the data frame based on two or more columns. For this, Dataframe.sort_values() method is used. This method sorts the data frame in Ascending or Descending order according to the columns passed inside the function. First, Let's Create a Dataframe: [GFGTABS]
    2 min read
  • How to Show All Columns of a Pandas DataFrame?
    Pandas limit the display of rows and columns, making it difficult to view the full data, so let's learn how to show all the columns of Pandas DataFrame. Using pd.set_option to Show All Pandas ColumnsPandas provides a set_option() function that allows you to configure various display options, includi
    2 min read
  • Count number of rows and columns in Pandas dataframe
    In Pandas understanding number of rows and columns in a DataFrame is important for knowing structure of our dataset. Whether we're cleaning the data, performing calculations or visualizing results finding shape of the DataFrame is one of the initial steps. In this article, we'll explore various ways
    3 min read
  • How to Delete a column from Pandas DataFrame
    Deleting data is one of the primary operations when it comes to data analysis. Very often we see that a particular column in the DataFrame is not at all useful for us and having it may lead to problems so we have to delete that column. For example, if we want to analyze the students' BMI of a partic
    2 min read
  • How to sum values of Pandas dataframe by rows?
    While working on the python pandas module there may be a need, to sum up, the rows of a Dataframe. Below are the examples of summing the rows of a Dataframe. A Dataframe is a 2-dimensional data structure in form of a table with rows and columns. It can be created by loading the datasets from existin
    3 min read
  • How to Filter DataFrame Rows Based on the Date in Pandas?
    Different regions follow different date conventions (YYYY-MM-DD, YYYY-DD-MM, DD/MM/YY, etc.).  It is difficult to work with such strings in the data. Pandas to_datetime() function allows converting the date and time in string format to datetime64. This datatype helps extract features of date and tim
    5 min read
  • How to Filter DataFrame Rows Based on the Date in Pandas?
    Filtering a DataFrame rows by date selects all rows which satisfy specified date constraints, based on a column containing date data. For instance, selecting all rows between March 13, 2020, and December 31, 2020, would return all rows with date values in that range. Use DataFrame.loc() with the ind
    2 min read
  • Show all columns of Pandas DataFrame
    Pandas sometimes hides some columns by default if the DataFrame is too wide. To view all the columns in a DataFrame pandas provides a simple way to change the display settings using the pd.set_option() function. This function allow you to control how many rows or columns are displayed in the output.
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences