Can we use a pandas data frame to calculate the next value using a previous value? A good example would be the Fibonacci numbers

Viewed 933

So I understand we can use pandas data frame to do vector operations on cells like

df = pd.Dataframe([a, b, c])
df*3

would equal something like :

0 a*3
1 b*3
2 c*3

but could we use a pandas dataframe to say calculate the Fibonacci sequence ? I am asking this because for the Fibonacci sequence the next number depends on the previous two number ( F_n = F_(n-1) + F_(n-2) ). I am not exactly interested in the Fibonacci sequence and more interested in knowing if we can do something like:

df = pd.DataFrame([a,b,c])
df.apply( some_func )

0 x1 a
1 x2 b
2 x3 c

where x1 would be calculated from a,b,c (I know this is possible), x2 would be calculated from x1 and x3 would be calculated from x2

the Fibonacci example would just be something like :

df = pd.DataFrame()
df.apply(fib(n, df))

0 0
1 1
2 1
3 2
4 2
5 5 
.
.
.
n-1 F(n-1) + F(n-2) 
1 Answers

You need to iterate through the rows and access previous rows data by DataFrame.loc. For example, n = 6

df = pd.DataFrame()

for i in range(0, 6):
    df.loc[i, 'f'] = i if i in [0, 1] else df.loc[i - 1, 'f'] + df.loc[i - 2, 'f']

df
     f
0  0.0
1  1.0
2  1.0
3  2.0
4  3.0
5  5.0
Related