【发布时间】:2015-06-03 10:27:41
【问题描述】:
我需要同时计算两个相互依赖的值。问题是a 和b 依赖于a 和b 的先前值。所以我们需要同时计算它们,同时参考循环的最后计算值。我到目前为止是这样的:
x = df.x # just a list containing randomly 1 and 0
df['a']=100 # 100 is just the starting value for a and b and shall be then overwritten by the while loop
df['b']=100
i=1
while i<len(df.index):
df.a[i] = x*((df.a.shift(1)*0.45)+(df.b.shift(1)*0.5))+abs(1-x)*df.a.shift(1)
df.b[i] = x*((df.b.shift(1)*0.5)+(df.a.shift(1)*0.59))+abs(1-x)*df.b.shift(1)
i+1
df 是一个数据帧。
目前我收到错误:ValueError: setting an array element with a sequence.
我也知道为什么会出现这个问题,请参阅this question。问题是,我该如何解决这个问题?可能有比while 循环更有效的解决方案...
【问题讨论】:
-
在 Python 中你可以做例如
a, b = some_op(a, b), other_op(a, b)使用右侧的旧值并在左侧分配两个新值。 -
解决这个 2 变量问题的一个常见方法是使用一个临时变量来存储 a 的“旧”值。所以像
old_a = a; a = get_new_a(a, b); b = get_new_b(old_a, b). -
我将如何实施这样的解决方案?
-
您报告的错误与您提出的问题无关。尝试将问题分开,以便您可以理解答案(以及我们的问题)。