2016-07-29 44 views
3

我有一个叫做数据的熊猫df。pandas df列上的嵌套“ifs”

我想要做的事,如:

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

,并可能有更多的列,这样我可以跟踪当几个条件都满足在一起。这有效,但速度慢,什么是更好的方法?

+0

'COUNT1 =总和(数据[ 'COL1']> 25)' –

回答

3

这是一种更好的方式去:

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

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

print count1 
print count2