简体   繁体   English

将功能创建的列追加到现有数据框

[英]Appending function created column to an existing data frame

I currently have a dataframe as below: 我目前有一个数据框,如下所示:

在此处输入图片说明

and wish to add a column, E, that is calculated based on the following function. 并希望添加一列E,该列基于以下函数进行计算。

def geometric_brownian_motion(T = 1, N = 100, mu = 0.1, sigma = 0.01, S0 = 20):
    dt = float(T)/N
    t = np.linspace(0, T, N)
    W = np.random.standard_normal(size = N)
    W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###
    X = (mu-0.5*sigma**2)*t + sigma*W
    S = S0*np.exp(X) ### geometric brownian motion ###
    return S

(originating from here ) (从这里开始

How to i create a time-series for all of the dates contained within the data-frame and append it? 如何为数据框中包含的所有日期创建时间序列并将其附加?

The function input parameters are as follows: 功能输入参数如下:

T = (#days between df row 1 and df last)/365 T =(df行1和df最后之间的#天)/ 365

N = # rows in data frame N =数据帧中的#行

S0 = 100 S0 = 100

As i understand the essense of question is how to apply some method to every column, taking into account, the fact that to calculate a new value you need an index from dataframe: 据我了解,问题的实质是如何将某种方法应用于每一列,同时考虑到要计算新值,您需要从数据框中获取索引这一事实:

I suggest you to extract index as separate column and use apply as usually. 我建议您将索引提取为单独的列,然后像往常一样使用apply。

from functools import partial
df['index'] = df.index
T = # precalculate T here
N = df.shape[0]
applying_method = partial(geometric_brownian_motion,T=T,N=N, S0=100)
df['E'] = df.apply(lambda row: applying_method(*row),axis=1)

Or if you rename columns of dataframe accroding to you function arguments: 或者,如果您重命名附加给您的函数参数的数据框的列:

df['E'] = df.apply(lambda row: applying_method(**row),axis=1)

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM