这是第一个数据集
<表类>
类型
周
价值
tbody><<tr>1 10 2 1 B1 50 D4 5 表类>
使用说明:
#use left join
df = df2.merge(df1, how='left', on=['type','week'], suffixes=('','_'))
#sorting for maximal values first per groups
df = df.sort_values(['type','week','value'], ascending=[True, True, False])
#create cumulative sums pre groups of values and add value_ from df1
df['val'] = df.groupby('week')['value'].cumsum().add(df['value_'])
#first rows per groups
m1 = ~df.duplicated(['type','week'])
#negative value_
m2 = df['value_'].lt(0)
#negative subtracted cumulative sum
m3 = df['val'].lt(0)
#first positive per groups after last nagative
m4 = df.groupby(['type','week'])['val'].shift().lt(0)
#final mask first part test first positive values per groups m1 & ~m2
#second part test negative values
mask = (m1 & ~m2) | (m2 & (m3 | m4))
#only for filtered rows add values of val with clip for convert negative to 0
df.loc[mask, 'value'] = df.loc[mask, 'val'].clip(lower=0)
df = df.sort_index()[['type','group','week','value']]
print (df)
type group week value
0 A 1 1 5
1 A 2 1 20
2 D 10 4 1
3 D 11 4 1
4 D 16 4 0