简体   繁体   中英

Python create new dataframe column based on different rows

So I am having dataframe which looks like this

       v1   v2
day1   x    x
day2   x    x
day3   x    x
day4   x    x
day5   x    x

What I need is to add new column v3 which will be the difference "today's v1 - yesterday's v2"

I've tried df[v3] = df[v1][1:] - df[v2][:-1]

But it looks like python is somehow mapping rows by timestamp and I am receiving "today's v1 - today's v2" as result except for first and last rows which are NaN.

IIUC,随着您的日子单调增加,您可以通过v2.shift()减去v1

df['v3'] = df.v1 - df.v2.shift()

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