我想找到某列中值的累加总和超过阈值的行(索引)。
我可以并且确实使用一个简单的循环来找到此位置,如下所示:
def sum_to(df, col, threshold):
s = 0
for r in df.iterrows():
if s + r[1][col] > threshold:
return r[0]
else:
s += r[1][col]
return len(df)
Run Code Online (Sandbox Code Playgroud)
但是,我想知道在Pandas中是否有更好/更精巧的方法来实现这一目标。
最简单的方法可能是
df[col].cumsum().searchsorted(threshold)
Run Code Online (Sandbox Code Playgroud)
但这是假设您的栏中没有负数。
| 归档时间: |
|
| 查看次数: |
629 次 |
| 最近记录: |