简体   繁体   中英

Pandas how to get sum of current value and next consecutive 2 values of a column and add to a new column

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

df = df[::-1]
df['num3'] = df.rolling(3).sum()
df[::-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM