简体   繁体   中英

How do I create a new column based on existing columns in pandas?

I am new to Python/pandas. I want to compute continuous returns based on "GOOG" Price. If the price is in column (a); How should I calculate the return in column (b) according to the following formula?

continuous returns =

在此处输入图像描述

I want to do this like the image below (calculating continuous returns in Excel) in Pandas DataFrame.

在此处输入图像描述

import pandas as pd

x = pd.DataFrame([2340, 2304, 2238, 2260, 2315, 2318, 2300, 2310, 2353, 2350],
                 columns=['a'])

Try:

x['b'] = np.log(x['a']/x['a'].shift())

Output:

      a         b
0  2340       NaN
1  2304 -0.015504
2  2238 -0.029064
3  2260  0.009782
4  2315  0.024045
5  2318  0.001295
6  2300 -0.007796
7  2310  0.004338
8  2353  0.018444
9  2350 -0.001276

You can use generator function with .apply :

import numpy as np
import pandas as pd

x = pd.DataFrame(
    [2340, 2304, 2238, 2260, 2315, 2318, 2300, 2310, 2353, 2350], columns=["a"]
)


def fn():
    old_a = np.nan
    a = yield
    while True:
        new_a = yield np.log(a / old_a)
        a, old_a = new_a, a


s = fn()
next(s)
x["b"] = x["a"].apply(lambda v: s.send(v))
print(x)

Prints:

      a         b
0  2340       NaN
1  2304 -0.015504
2  2238 -0.029064
3  2260  0.009782
4  2315  0.024045
5  2318  0.001295
6  2300 -0.007796
7  2310  0.004338
8  2353  0.018444
9  2350 -0.001276

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