达到特定阈值后,在df列中获取部分值的总和

时间:2019-08-23 16:50:20

标签: python pandas dataframe

我需要开始在df的一列中添加值,并返回总和达到某个阈值的行。最简单的方法是什么?

例如

threshold = 86

    values    ID
1   42       xxxxx
2   34       yyyyy
3   29       vvvvv
4   28       eeeee

应返回第3行

3 个答案:

答案 0 :(得分:1)

import pandas as pd

df = pd.DataFrame(dict(values=[42, 34, 29, 28], ID=['x', 'y', 'z', 'e']))

threshold = 86

idx = df['values'].cumsum().searchsorted(threshold)
print(df.iloc[idx])

Try it here

输出:

values    29
ID         z
Name: 2, dtype: object

请注意,df.values具有特殊的熊猫含义,因此df['values']是不同且必要的。

答案 1 :(得分:0)

这应该有效

df['new_values'] = df['values'].cumsum()

rows = df[df['new_values']==threshold].index.to_list()

答案 2 :(得分:0)

另一种方式

df['values'].cumsum().ge(threshold).idxmax()

Out[131]: 3

df.loc[df['values'].cumsum().ge(threshold).idxmax()]

Out[133]:
values       29
ID        vvvvv
Name: 3, dtype: object