Gluons
Gluons

Reputation: 19

Pandas - Division within a single column issue

I have a column of float64 data indexed by datetime. I need to divide one row by the row before it.

In the instance below I would need to start in the dataframe with 1.1133/1.1134 then take the result and store it in a new column. Then move down a row and repeat.

In excel you can do this very easy say B2/B3 and drag it down. Is there a method I can use in a Pandas Dataframe to mimic this? I have tried various configs with the divide function, but to no good result. Any help on this would be great to point me in the right direction.

Time             Close

4/26/2019 11:08 1.1133 

4/26/2019 11:07 1.1134

4/26/2019 11:06 1.1135

4/26/2019 11:05 1.1135

4/26/2019 11:04 1.1135

4/26/2019 11:03 1.1135

Upvotes: 0

Views: 151

Answers (2)

sslloo
sslloo

Reputation: 521

You can do this in three steps:

  1. Duplicate dataFrame
  2. Shift the duplicate dataframe (move index by one row)
  3. Create new column based on substraction

df["new_columns"] = (df["Close"] / df["Close"].shift(1))

I am am not exactly sure if you are looking shift(1) or shift(-1) shift move all index by the given value.

Upvotes: 1

guo
guo

Reputation: 1

I think you need this

df = pd.DataFrame([['a',1,41],['a',2,98],['a',3,53],['b',1,15],['b',2,64],['b',3,36]], columns=['date', 'xart','yart']) 

  date xart yart
0   a   1   41
1   a   2   98
2   a   3   53
3   b   1   15
4   b   2   64
5   b   3   36

df['change'] = df['xart'].pct_change(1)
df

  date xart yart change
0   a   1   41  NaN
1   a   2   98  1.000000
2   a   3   53  0.500000
3   b   1   15  -0.666667
4   b   2   64  1.000000
5   b   3   36  0.500000

Upvotes: 0

Related Questions