[英]How to pick values from column and add them to a mathematical function (Pandas)
I'm ttrying to pick all the values from a dataframe column I have and apply them to a mathematical function.我正在尝试从我拥有的数据框列中选择所有值并将它们应用于数学函数。 Heres how the data looks:以下是数据的外观:
Year % PM
1 2002 3
2 2002 2.3
I am trying to apply this function :我正在尝试应用此功能:
M = 100000
t = (THE PERCENTAGE FROM THE DATAFRAME)/12
n = 15*12
PM = M*((t*(1+t)**n)/(((1+t)**n)-1))
print(PM)
And my goal is to do it to all the rows and append the value of each result to PM in the dF我的目标是对所有行执行此操作并将每个结果的值附加到 dF 中的 PM
You can just add the formula as a column directly to the DF, creating t_div_12
as a vector from the column as below:您可以将公式作为一列直接添加到 DF,从列中创建t_div_12
作为向量,如下所示:
M = 100000
n = 15*12
t_div_12 = df["%"]/12
df["PM"] = M*((t_div_12 *(1+t_div_12 )**n)/(((1+t_div_12)**n)-1))
df['PM'] = df['%'].map(lambda t: M*(((t/12)*(1+(t/12))**n)/(((1+(t/12))**n)-1)))
First, I would avoid using constants, which are not repeated in the code.首先,我会避免使用在代码中没有重复的常量。 You can apply this function to your dataframe by using this code snippet:您可以使用以下代码段将此函数应用于您的数据框:
dF = pd.DataFrame([[2002, 3], [2002, 2.3]], columns=["Year", "%"])
dF['PM'] = 100000*((dF["%"]/12*(1+dF["%"]/12)**(15*12))/(((1+dF["%"]/12)**(15*12))-1))
It will give you:它会给你:
Year % PM
0 2002 3.0 25000.000000
1 2002 2.3 19166.666667
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.