1

The development factor from time t to time t+1 is At+1 / At. I am trying to apply this calculation to a pandas DataFrame that looks something like below:

   T0   T1   T2
0  100  200  250
1  80   120  150

Starting from another post, I tried the following

f = lambda x: np.divide(x[1], x[0])
df.applymap(f, axis=1)

but I am getting an error an index error. I would like the output to be

   T0_T1  T1_T2
0  2.0    1.25
1  1.5    1.25
Community
  • 1
  • 1
Zachary Luety
  • 13
  • 1
  • 3

1 Answers1

1

IIUC you need change applymap to apply:

f = lambda x: np.divide(x[1], x[0])
df1 = df.apply(f, axis=1)
print (df1)
0    2.0
1    1.5
dtype: float64

If function is more complicated:

def f(x):
    print (x)
    #add code
    return x.T1 / x.T0

df1 = df.apply(f, axis=1)
print (df1)
0    2.0
1    1.5
dtype: float64

But better is used vectorized faster solution with div:

print (df.T1.div(df.T0))
0    2.0
1    1.5
dtype: float64

print (df.T1 / df.T0)
0    2.0
1    1.5
dtype: float64

EDIT by commnet:

Divide by shifted df, last remove first column by iloc:

df1 = df.div(df.shift(axis=1))
print (df1)
   T0   T1    T2
0 NaN  2.0  1.25
1 NaN  1.5  1.25

df1 = df1.iloc[:,1:]
print(df1)
    T1    T2
0  2.0  1.25
1  1.5  1.25
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • I edited the question to clarify my intention, I understand how to divide two individual columns but I want to apply the calculation to the entire DataFrame, – Zachary Luety Feb 17 '17 at 04:40