Python 当值达到某个阈值时,获取df列中值的部分和

Python 当值达到某个阈值时,获取df列中值的部分和,python,pandas,dataframe,Python,Pandas,Dataframe,我需要开始在df中的一列中添加值,并返回一行,其中总和达到某个阈值。最简单的方法是什么 e、 g 应该返回第3行 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]) 输出: val

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

e、 g

应该返回第3行

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])

输出:

values    29
ID         z
Name: 2, dtype: object
请注意,
df.values
有一个特殊的含义,因此
df['values']
是不同的,并且是必要的。

这应该有效

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

rows = df[df['new_values']==threshold].index.to_list()
另一种方式

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

要添加的
是什么?必须有一个累积和或某种滚动操作。您要添加的值他们正在DF本身中添加值。这可不是什么数字。“我需要开始在其中一列中添加值”-这是一个
cumsum
是的,roganjosh是对的,我需要的是一个cumsum,Alex Hall的解决方案很好
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