• 0

[Python] Subset pandas DataFrame by column value


Question

Suppose I have a pandas dataframe df:

Index Var1 Var2 Var3

row1 1 0 0

row2 1 1 1

row3 3 5 1

row4 1 5 1

row5 0 0 0

 

The problem I am having is that I want to get the rows where all the column values are non-zero.

So I want to get row2, row3, and row4 since all the values in their column are not zero.

 

I have been looking on subsetting the data, but the number of columns I have and their names can vary.

A lot of the answers I found online tell me to use boolean but that would require me to know the column names beforehand.

 

Any help is appreciated. Don't tell me to "go search google" or do that lmgtfy, that is rude and I already have searched, and no, this is not homework, this is for a work project, and yes, I am still learning Python, that is why I do not know the answer to this simple elementary problem. 

 

edit, tried to fix the formatting, but I guess the forum software is buggy

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

Basic idea (pseudocode):

let list := new empty list of rows
for each row in rows
    let foundZero := false
    for each element in row
        if element equals 0 then 
            foundZero := true
    if not foundZero then
        list.add(row)

// At this point list contains all rows that don't contain zeroes
 

I don't know the specifics of the API you're using so you still need to figure out some details but algorithmically that's what you need to do.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.