【问题标题】:Circular dependency in pandas dataframe熊猫数据框中的循环依赖
【发布时间】:2015-06-20 18:17:23
【问题描述】:

以下代码对掷硬币的结果进行投注。您从 100 英镑开始,每次翻转的风险为 5%,但由于我的代码根据您的起始余额计算下注大小,因此下注始终为 5 英镑。

import pandas
import matplotlib.pyplot as plt

start_bal = 100.0 #start off with £100
risk = 0.05 # risk 5% on each bet

#create an empty data frame.
a = pandas.DataFrame()

#create a list of coin toss results, 1 is win, -1 is lose
a['Result'] = [1,1,1,1,-1,-1,1,1,1,-1,-1,1,1,-1,-1,-1,1,1]

#your bet size is a % of your starting balance
a['bet'] = start_bal*risk
#record profit or loss based on coin toss
a['pnl'] = a.Result * a.bet
#increase/decrease balance
a['bal'] = start_bal + a.pnl.cumsum()

#plot balance
plt.plot(a.bal)

我想做的是在每次下注后根据您当时的余额重新计算下注大小,这样您在余额增加时下注更多,在余额减少时下注更少。这意味着“bal”取决于“赌注”,而“赌注”又取决于“bal”,所以我最终得到了一个循环关系。

这可能吗?我是否需要一次遍历数据帧一行,重新计算该特定索引处的“bal”和“bet”?

谢谢。

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    一个简单的单行:

    results = start_bal * (1 + risk * a.Result).cumprod()
    >>> results
    0     105.000000
    1     110.250000
    2     115.762500
    3     121.550625
    4     115.473094
    5     109.699439
    6     115.184411
    7     120.943632
    8     126.990813
    9     120.641272
    10    114.609209
    11    120.339669
    12    126.356653
    13    120.038820
    14    114.036879
    15    108.335035
    16    113.751787
    17    119.439376
    Name: Result, dtype: float64
    
    results.plot()
    

    【讨论】:

    • 是的,这就是我所追求的!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2015-09-19
    • 2020-11-20
    • 2020-07-05
    • 2017-10-29
    相关资源
    最近更新 更多