What is the right/pythonic way to do math on a few indexed elements in a Pandas Dataframe?
I tried a few ways but they seem awkward and confusing:
df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6, 7, 9, ]})
df['y'] = df['x'] / 2
print(df)
def printEpr(x):
print(F"""End Point Rate:
{epr} dy/dx""")
epr = (df['y'][7] - df['y'][0]) / (df['x'][7] - df['x'][0])
printEpr(epr)
epr = (
(df.iloc[[-1], [1]].values - df.iloc[[0], [1]].values)
/ (df.iloc[[-1], [0]].values - df.iloc[[1], [0]].values))
printEpr(epr)
#epr = (df['y'] - df.iloc[0, 'y']) / (df.iloc[-1, 'x'] - df.iloc[0, 'x'])
#printEpr(epr)
yind = df.columns.get_loc('y')
xind = df.columns.get_loc('x')
epr = (df.iloc[-1, yind] - df.iloc[0, yind]) / (df.iloc[-1, xind] - df.iloc[0, xind])
printEpr(epr)
#epr = (df.iloc[-1, 'y'] - df.iloc[0, 'y']) / (df.iloc[-1, 'x'] - df.iloc[0, 'x'])
#printEpr(epr)
With results:
x y
0 1 0.5
1 2 1.0
2 3 1.5
3 4 2.0
4 5 2.5
5 6 3.0
6 7 3.5
7 9 4.5
End Point Rate:
0.5 dy/dx
End Point Rate:
[[0.57142857]] dy/dx
End Point Rate:
0.5 dy/dx