How to calculate rows where it has values in at least 3 columns

  • #1
53
6
I am trying to count number of rows that has values in at least 3 columns so the output based on the image shared should be 4. I tried using the code below but it is resulting in the same shape as the whole table which is 7.

Python:
counts = df[(df[['a', 'b', 'c', 'd]] != 'no_label').count(axis=1) >= 3]
 

Attachments

  • p3.png
    p3.png
    2.3 KB · Views: 321

Answers and Replies

  • #2
35,335
11,644
sum(row.count("no_label")<2 for row in df)
If your table includes the header but you don't want to count that: subtract 1.
 
  • #3
53
6
thank you for this suggestion. but what if i only want to check from these columns a,b,c, and d? as I have other columns e,f,g that also has the 'no_label' value but I don't want to consider them,
 
  • #5
53
6
i wanted to do it this way so that i can select the columns that could be in other position in the dataframe:

Python:
cols = ['a', 'b', 'c', 'd'']

sum(row[cols].count("no_label") < 2 for row in df)

but it gives me this error :

TypeError: string indices must be integers, not list

what can i do to use the column names explicitly instead. thanks
 
  • #6
35,335
11,644
Where do the column labels come from? Are they the first row of you array? I wouldn't do that, it is bad style. Select them based on integers.
If you absolutely need strings convert them to integers for the sum.
 
  • #7
53
6
yes they are but in this case there are more than 10 columns which makes it difficult to determine the location of the column using integers.
 
  • #8
35,335
11,644
You keep changing the task. Why don't you show what exactly you want to do?

cols={'a':0,'b':1,'c':2,'d':3}
sum(row[cols['a']:cols['c']].count("no")>0 for row in df)

Or, if the first row of df has the column names:
Code:
cols2={}
for x,y in enumerate(df[0]):
  cols2[y]=x
 
  • Like
Likes msn009 and Tom.G
  • #9
53
6
thanks. sorry for not explaining the scenario in detail.
 

Related Threads on How to calculate rows where it has values in at least 3 columns

Replies
2
Views
2K
  • Last Post
Replies
2
Views
2K
Replies
9
Views
4K
  • Last Post
Replies
7
Views
533
Replies
6
Views
4K
Replies
5
Views
793
Replies
7
Views
817
Replies
5
Views
775
Replies
1
Views
697
Top