flgdev
flgdev

Reputation: 487

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.

Upvotes: 1

Views: 43

Answers (1)

Andy L.
Andy L.

Reputation: 25269

IIUC, as your days monotonic increasing, you may subtract v1 by v2.shift()

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

Upvotes: 2

Related Questions