cumsum pandas 达到特定值 - python pandas

cumsum pandas up to specific value - python pandas

Cumsum 直到值超过特定数量:

假设我们有两个数据框 A、B,如下所示:

A = pd.DataFrame({"type":['a','b','c'], "value":[100, 50, 30]})
B = pd.DataFrame({"type": ['a','a','a','a','b','b','b','c','c','c','c','c'], "value": [10,50,45,10,45,10,5,6,6,8,12,10]})

两个数据框看起来像这样。

>>> A
  type  value
0    a    100
1    b     50
2    c     30

>>> B
   type  value
0     a     10
1     a     50
2     a     45
3     a     10
4     b     45
5     b     10
6     b      5
7     c      6
8     c      6
9     c      8
10    c     12
11    c     10

对于数据框 A 中 "type" 中的每个组,我想将 B 中的列值添加到 A 中列值中指定的数量。我还想计算B 中添加的行。我一直在尝试使用 cumsum() 但我不知道要在达到该值时停止求和,

输出应该是:

  type  value
0    a      3
1    b      2
2    c      4

谢谢,

合并之前的两个数据框应该会有所帮助:

import pandas as pd
df = pd.merge(B, A, on = 'type')
df['cumsum'] = df.groupby('type')['value_x'].cumsum()
B[(df.groupby('type')['cumsum'].shift().fillna(0) < df['value_y'])].groupby('type').count()

# type  value
#    a      3
#    b      2
#    c      4

假设 B['type'] 与示例案例一样进行排序,这是一个基于 NumPy 的解决方案 -

IDs = np.searchsorted(A['type'],B['type'])
count_cumsum = np.bincount(IDs,B['value']).cumsum()
upper_bound = A['value'] + np.append(0,count_cumsum[:-1])
Bv_cumsum = np.cumsum(B['value'])
grp_start = np.unique(IDs,return_index=True)[1]
A['output'] = np.searchsorted(Bv_cumsum,upper_bound) - grp_start + 1