如何将上一行的值加到下一行的Pandas上

wbrvyc0a  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(123)

我有一个具有以下规格的 Dataframe

| ID |  Name| count  |
  | -- |----  | ----   | 
  | 1  |  A   |  75    |
  | 2  |  B   |  10    |
  | 3  |  A   |  15    |
  | 4  |  A   |  10    |
  | 5  |  A   |  5     |
  | 6  |  A   |  3     |

如果我将计数的阈值设置为15,我希望下面的行均匀地相加。

| ID |  Name |  count |
  | -- |----   | ----   | 
  | 1  |  A    |    15  |
  | 2  |  B    |    10  |
  | 3  |  A    |    30  |
  | 4  |  A    |    25  |
  | 5  |  A    |    20  |
  | 6  |  A    |    18  |

ID 1中的75将根据组“名称”相加,并且始终基于阈值。请提供建议

vhipe2zx

vhipe2zx1#

IIUC您可以执行以下操作:

def distribute(sr, thres=15):
    idxmax = sr.idxmax()
    remain = max((sr[idxmax] - thres) / max(len(sr) - 1, 1), 0)
    return np.where(sr.index == idxmax, min(sr[idxmax], thres), sr + remain)

df['newcount'] = df.groupby('Name')['count'].transform(distribute, thres=15)

输出:
| 识别号|姓名|计数|新计数|
| - ------|- ------|- ------|- ------|
| 1个|A类|七十五|十五|
| 第二章|乙|十个|十个|
| 三个|A类|十五|三十|
| 四个|A类|十个|二十五|
| 五个|A类|五个|二十个|
| 六个|A类|三个|十八|

相关问题