Reputation: 3421
I have a data frame column with numbers. I need to add a new column to the data frame where the value of the new column is sum of the current value and the next two values of this column. The last two rows of the new column should be NAN. eg: if my column is
p=[1,2,3,4,5,6,7,8]
df=pd.DataFrame({'num':p})
#dummy data
The first value of the new column should be 1+2+3, second 2+3+4 and so on. Right now I am doing by converting the column to list and then doing the calculations.
p=df['num'].tolist()
ls=[]
for (i,v) in enumerate(p):
try:
val=v+p[i+1]+p[i+2]
ls.append(val)
except:
ls.append(np.NAN)
and finally adding the list to data frame
df['rolled']=ls
Is there any way we can do this by pandas itself? I tried rolling mean, does not work the way I want it, is there any special window in rolling mean which can get the output in required format?
Thanks in advance
Upvotes: 0
Views: 871