繁体   English   中英

查找行的索引,其中直到该索引为止的所有行的总和为给定的数字

[英]Find index of row where all the rows up until that index sum to a given number

我有以下数据框:

|---------------------|------------------|
|        Cost         |    Country       |
|---------------------|------------------|
|          12         |         34       |
|---------------------|------------------|
|          20         |         34       |
|---------------------|------------------|
|          21         |         34       |
|---------------------|------------------|

我想获取前n行,其成本值之和小于40。因此,在上述情况下,我想创建一个仅包含前2行的新数据框。 有没有一种有效的方法可以在数据帧中做到这一点而无需遍历每一行?

您可以使用pandas.DataFrame.cumsum()返回DataFrame或Series元素的累积总和:

df = pd.DataFrame({'Cost': [12, 20, 21], 'Country': [34, 34, 34]})
cumSumOfCost = df['Cost'].cumsum()
mask_cumSumBelow40 = cumSumOfCost < 40
df_sumBelow40 = df.loc[mask_sumBelow40]

您可以使用cumsum()来获取成本值总和小于40的前n行。

DF [DF [ '费用'。cumsum()<40]

暂无
暂无

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

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