简体   繁体   English

计算满足熊猫数据框中某些求和条件的行数

[英]Counting the number of rows that meet certain sum condition in pandas dataframe

I tried to get the number of rows when the total values of the first x rows in certain column in pandas dataframe exceed certain values. 当pandas数据框中的某些列中的前x行的总值超过某些值时,我尝试获取行数。 I've read several solutions, but not exactly what I am looking for. 我已经阅读了几种解决方案,但并非完全符合我的要求。 Basically I can do this with a loop as shown in the following codes. 基本上,我可以使用以下代码所示的循环来执行此操作。 I just wondering whether there is any commando in python to do this without loop? 我只是想知道是否在python中有任何突击队做到这一点而没有循环?

import pandas as pd

df = pd.DataFrame({'A': pd.Series(range(1, 10), index = \
                  range(1, len(range(1,10))+1))})
Count = 0

for i in df.loc[:, 'A']:
    Count += i
    if (Count > 5):
        break

print('Row index:', i)

this codes provides me what I want that the number of row when the sum of x first row in column A exceed 5 is three. 这段代码为我提供了我希望当A列中x第一行的总和超过5时的行数。

thanks 谢谢

cumsum + idxmax应该可以工作:

df.A.cumsum().gt(5).idxmax()

3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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