简体   繁体   中英

How to change DataFrame Series from price to percentage with pandas/python

I have a pandas dataFrame with date,time and stock price like this:

+------------+-------+-------+-------+
|            | 08:01 | 08:02 | 08:03 |
+------------+-------+-------+-------+
| 01/01/2016 | 50    | 50.5  | 50.7  |
+------------+-------+-------+-------+
| 02/01/2016 | 49.6  | 49.5  | 49.6  |
+------------+-------+-------+-------+

Now I would like to change the prices to price changes on the day. The first price would always be 0%. It should look something like this:

+------------+-------+--------+-------+
|            | 08:01 | 08:02  | 08:03 |
+------------+-------+--------+-------+
| 01/01/2016 | 0     | 0.01   | 0.014 |
+------------+-------+--------+-------+
| 02/01/2016 | 0     | -0.002 | 0     |
+------------+-------+--------+-------+

The formula is: (stockPrice/stockOpenPrice)-1

How can I code this transformation?

Use difference by div with first column selected by iloc and last substract 1 :

print (df.div(df.iloc[:, 0], axis=0) - 1)
            08:01     08:02  08:03
01/01/2016    0.0  0.010000  0.014
02/01/2016    0.0 -0.002016  0.000

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