user
user

Reputation: 2103

Nested "ifs" on pandas df columns

I have a pandas df called data.

I want to do something like:

for i in range(data["col1"].count()):
  if data["col1"][i] > 25:
    count1 += 1
    if data["col2"][i] > 35:
      count2 += 1

and possibly with more columns so that I can keep track of when several conditions are met together. This works but it is slow, what is a better way?

Upvotes: 3

Views: 120

Answers (2)

Merlin
Merlin

Reputation: 25659

count1 = df[df["col1"] > 25].count().values
count2 = df[(df["col1"]> 25) & (df["col2"]>35)].count().values

print count1
print count2

Upvotes: 1

piRSquared
piRSquared

Reputation: 294488

This is a better way to go:

cond1 = data.col1 > 25
cond2 = data.col2 > 35

count1 = cond1.sum()
count2 = (cond1 & cond2).sum()

Upvotes: 3

Related Questions