pandas 数据框中的循环依赖 [英] Circular dependency in pandas dataframe

查看:62
本文介绍了 pandas 数据框中的循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在掷硬币的结果上下注.您以100英镑开始,每次下注的风险为5%,但是由于我的代码根据您的起始余额计算赌注大小,因此赌注始终为5英镑.

The following code places bets on coin flip results. You start with £100 and risk 5% on each flip, but because my code calculates bet size based on your starting balance, the bet is always £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"取决于"bet",而"bet"又取决于"bal",因此我最终得到一种循环关系.

What I would like to do is re-calculate bet size after each bet depending on your balance at that time so you're betting more when your balance increases and less when it decreases. This would mean that 'bal' depends on the 'bet', which in turn depends on 'bal' so I end up with a circular relationship.

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

Is this possible to do? Would I need to iterate through the dataframe one row at a time, re-calculating the 'bal' and 'bet' at that particular index?

谢谢.

推荐答案

一个简单的班轮:

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()

这篇关于 pandas 数据框中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆