Python Forum
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
DataFrame Calculation
#1
It is easy to add a new column to store the results of calculation on the same row as below.
I need to add a column df["d"] that will contain the results of calculation with current row i and next row i+1
something like: df["d"][i] = (df["b"][i] - df["a"][i+1]) / df["a"][i+ 1]
I can use "for loop" to do that but wondering if another better way. thanks

import pandas as pd

df = pd.DataFrame({"a": [11,12,13,14,15,16],
                   "b": [15,20,30,20,30,50]})
df["c"] = (df["b"] - df["a"]) / df["a"]
print(df)
Reply
#2
Hi Ian,

How about the simple assignment line below:
df['e']=[9,8,7,6,5,4]
df
Out[67]:
a b e
0 11 15 9
1 12 20 8
2 13 30 7
3 14 20 6
4 15 30 5
5 16 50 4

your case above seems similar to what I'm doing and posted about earlier titled "DataFrame simple calculation" which I still have no answer/solution for, same calculation in the data frame (which is calculating the returns against each row/trade day.

In my case I am trying to assign the result to a new dataframe called [ret], but the results I get seem to always zero, see below applied your dataframe sample above:
df = pd.DataFrame({"a": [11,12,13,14,15,16],
                   "b": [15,20,30,20,30,50]})

ret=(df.a[1:]-df.a[:-1])/df.a[:-1]

ret
Out[63]:
0 NaN
1 0.0
2 0.0
3 0.0
4 0.0
5 NaN
Name: a, dtype: float64
Reply
#3
So just to get to your sample, you can use the below line without a loop should suffice:
df["c"] = (df["b"] - df["a"]) / df["a"]
You can also assign the result to a new dataframe:
newDF = (df["b"] - df["a"]) / df["a"]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  looping calculation in dataframe duncipe 2 1,948 Mar-21-2020, 10:18 AM
Last Post: duncipe

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020