简体   繁体   中英

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?

This is a better way to go:

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

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

print count1
print count2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM