【问题标题】:Ratio of [value in cell to the left] to [sum of values above cell to the left] into a new column using pandas使用pandas将[左侧单元格中的值]与[左侧单元格上方值的总和]的比率放入新列
【发布时间】:2021-05-05 19:33:37
【问题描述】:

我在一个名为 ACTION_DATA 的数据框中有一个名为 Bets of poker bets 的列。我想创建一个具有下注底池比率(底池百分比)的新列

投注底池比率等于投注列中同一行的投注除以投注列中所有先前投注的总和。前两个投注应始终标记为“小盲注”和“大盲注” .

例如,对于每个 Bets 列,我想要一个 Bet-to-Pot Ratio 列,显示该比率如下:

| Bets | Bet-To-Pot-Ratio | Formula 
| -------- | -------------- |-----|
| .02    |  Small Blind     | 
| .05   |  Big Blind        | 
|.15 | 214% | .15/(.02 + .05)


| Bets | Bet-To-Pot-Ratio |Formula 
| -------- | -------------- |---| 
| .02    |  Small Blind      | 
| .05   |  Big Blind         | 
| .17 | 243% | .17/(.02 + .05)

| Bets | Bet-To-Pot-Ratio | Formula
 | -------- | -------------- |---| 
| .02    |  Small Blind      | 
| .05   |  Big Blind         | 
| .05 | 71% | .05/(.02 + .05) | 
|.05| 42% | .05/(.02 + .05 + .05)|
|.05| 29% | .05/(.02 + .05 + .05 + .05)|
|.03| 14% |.03/(.02 + .05 + .05 + .05 + .05)|

| Bets | Bet-To-Pot-Ratio | Formula
| -------- | -------------- |---| 
| .02    |  Small Blind      | 
| .05   |  Big Blind         | 
| .1 |  .1/(.02 + .05) |
|.2| 118% | .2/(.02 + .05 + .1)|
|.99| 268% | .99/(.02 + .05 + .1 + .2)|
|2.87| 211% |2.87/(.02 + .05 + .1 + .2 + .99)|

我尝试了一些跨列的计算,如下所示,但我认为我需要计算行数

import pandas as pd
df = [0, 0, 0]
df = pd.DataFrame(df).transpose()
df.columns = ['Bet Size', 'Pot', '% of Pot']

df['Pot'][0] = 0
df['% of Pot'][0] = 0

for _ in range(1, 10):
  df.loc[_, 'Bet Size'] = df.loc[_-1, 'Bet Size']+1
  df.loc[_, 'Pot'] = df.loc[_, 'Bet Size']+100
  df.loc[_, '% of Pot'] = df.loc[_-1, 'Pot']+df.loc[_, 'Pot'] + 1
df

【问题讨论】:

    标签: pandas dataframe sum percentage division


    【解决方案1】:

    您可以使用shift()cumsum() 得到答案:

    bets = [0.02, 0.05, 0.1, 0.2, 0.99, 2.87]
    df = pd.DataFrame({ "bets" : bets})
    
    df['ratio'] = df['bets']/(df['bets'].shift(1).cumsum())
    
    print(df)
    
       bets     ratio
    0  0.02       NaN
    1  0.05  2.500000
    2  0.10  1.428571
    3  0.20  1.176471
    4  0.99  2.675676
    5  2.87  2.110294
    

    【讨论】: