Below you find the code I wrote to calculate a relative change in value of df.a and df.b while df is a dataframe. What has to be calculated is basically df["c"] = df.a/df.a.iloc[df.d].values
. df.d is set equal to df.t if df.a/df.a.iloc[df.d].values
is bigger or smaller than df.b/df.b.iloc[df.d].values * (1+ tolerance)
The problem is that the code currently brings the following error code: ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index 2011-01-01 00:00:00')
and I absolutely don't know why...
import pandas as pd
import numpy as np
import datetime
randn = np.random.randn
rng = pd.date_range('1/1/2011', periods=10, freq='D')
df = pd.DataFrame({'a': [1.1, 1.2, 2.3, 1.4, 1.5, 1.8, 0.7, 1.8, 1.9, 2.0], 'b': [1.1, 1.5, 1.3, 1.6, 1.5, 1.1, 1.5, 1.7, 2.1, 2.1],'c':[None] * 10},index=rng)
df["d"]= [0,0,0,0,0,0,0,0,0,0]
df["t"]= np.arange(len(df))
tolerance = 0.3
def set_t(x):
if df.a/df.a.iloc[df.d].values < df.b/df.b.iloc[df.d].values * (1+tolerance):
return df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t
elif df.a/df.a.iloc[df.d].values > df.b/df.b.iloc[df.d].values * (1+tolerance):
return df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t
#The conditions in part one are exactly the same as in part 2, only first it says smaller than, and in the second part is bigger than df.b/df.b.iloc[df.d].values * (1+tolerance)
df['d'] = df.apply(set_t, axis =1)
#df["d"]= [0,0,0,3,3,3,6,7,7,7] this should be the coutcome for d
df["c"] = df.a/df.a.iloc[df.d].values
The application of (df.a/df.a.iloc[df.d].values).all() < (df.b/df.b.iloc[df.d].values).all()
or .any()
does not lead to the deired outcome, since it only checks when the data currently set is TRUE or FALSE, but it does not set the new value.
The desired outcome looks like this:
a b c d t
2011-01-01 1.1 1.1 1.000000 0 0
2011-01-02 1.2 1.5 1.090909 0 1
2011-01-03 2.3 1.3 2.090909 0 2
2011-01-04 1.4 1.6 1.000000 3 3
2011-01-05 1.5 1.5 1.071429 3 4
2011-01-06 1.8 1.1 1.285714 3 5
2011-01-07 0.7 1.5 1.000000 6 6
2011-01-08 1.8 1.7 1.000000 7 7
2011-01-09 1.9 2.1 1.055556 7 8
2011-01-10 2.0 2.1 1.111111 7 9
Any ideas how to solve that?