Writing two objects at the same time
I need to calculate two interdependent values at the same time. The problem is that a
both b
depend on the previous value a
and b
. Therefore, we need to calculate them at the same time, referring to the last calculated values of the loop. What I am so far is:
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 is DataFrame. I am currently getting the error:ValueError: setting an array element with a sequence.
I also know why I am getting this problem, see this question . The question is, how can I solve this? Perhaps a more efficient solution than a loop while
...
source to share
I can see that df.a
and df.b
are both sequences. This way you can use map to get the result.
Example:
l = [1, 2, 3]
set_negative = lambda x: x * -1 # Some function o lammbda that receives a sinble argument
ml = map(set_negative, l) # ml = [-1, -2, -3]
In your case, you can write your code like this:
in_a = lambda _: x*((df.a.shift(1)*0.45)+(df.b.shift(1)*0.5))+abs(1-x)*df.a.shift(1)
in_b = lambda _: x*((df.b.shift(1)*0.5)+(df.a.shift(1)*0.59))+abs(1-x)*df.b.shift(1)
df.a = map(in_a, df.a)
df.b = map(in_b, df.b)
source to share