迭代特定列直到 pandas 中的某个值

iterate over specific column up to a certain value in pandas

A = pd.DataFrame({"type":['a','b','c', 'd','e'], "cost basis":[50, 40, 30, 20, 10], "value":[5, 25, 40, 10, 20]})

我希望遍历“值”列直到达到某个值或按降序求和。假设是 50,而如果下一个数字超过该值,则迭代将停在那里。

不确定你想要什么,但如果我理解正确的话:

尝试通过 cumsum():

out=A.loc[A['value'].cumsum().le(50)]

如果想按降序排列则使用sort_values()+cumsum():

out=A.loc[A.sort_values('value',ascending=False,ignore_index=True)['value'].cumsum().le(50)]

您可以使用两个函数实现此目的:cumsumargmax

import numpy as np
import pandas as pd
A = pd.DataFrame({"type":['a','b','c', 'd','e'], "cost basis":[50, 40, 30, 20, 10], "value":[5, 25, 40, 10, 20]})

# Cummulated sum of array A
acumsum = np.cumsum(A.value.values)

# Determine the first index where the value is greater than 50:
idx = np.argmax(acumsum > 50)

print(idx)