[英]How to calculate a pandas column based on the previous value in the same column that is calculated?
I want to achieve the following table, where the values in "md" needs to be calculated:我想实现下表,其中需要计算“md”中的值:
msotc md
0 0 0
1 1 1
2 2 3
3 3 7
4 4 15
5 5 31
6 6 63
7 7 127
Given:鉴于:
Solutions (I think):解决方案(我认为):
import pandas as pd
import numpy as np
msotc = 7
sopd = 1 # (= not fixed, could be eg. 0.5)
soss = 2 # (= not fixed, could be eg. 1.05)
arr = [np.NaN] * (msotc + 1)
arr[0] = 0
data = {
"msotc": range(0, msotc + 1, 1),
"md": arr
}
df = pd.DataFrame(
data=data
)
# df["md"] = (df["md"].shift(1) * soss) + sopd <- This doesn't work
You can use math to convert your formula into a geometric series.您可以使用数学将公式转换为几何级数。
md[n] = md[n-1]*soss + sopd
expressed in terms of md[0]
and using the formula for the sum of powers:用md[0]
表示并使用幂和的公式:
md[n] = md[0]*soss**(n-1) + sopd * (soss**n - 1)/(soss-1)
Thus no need to loop, you can vectorize:因此不需要循环,你可以矢量化:
msotc = 7
sopd = 1
soss = 2
md0 = 0
n = np.arange(msotc+1)
df = pd.DataFrame({'msotc': n, 'md': md0*soss**np.clip(n-1, 0, np.inf) + sopd*(soss**n-1)/(soss-1)})
output: output:
msotc md
0 0 0.0
1 1 1.0
2 2 3.0
3 3 7.0
4 4 15.0
5 5 31.0
6 6 63.0
7 7 127.0
This should work fine.这应该可以正常工作。 It is quite easy to understand, just a simple loop.很容易理解,就是一个简单的循环。
arr = [0] * (msotc + 1)
for i in range(msotc + 1):
if i == 0:
continue
arr[i] = (arr[i - 1] * soss) + sopd
Try this:尝试这个:
import pandas as pd
msotc = 7
sopd = 1
soss = 2
msotc_vals = []
arr = [0]
for val in range(msotc + 1):
msotc_vals += [val]
arr += [arr[-1] * soss + sopd]
data = {"msotc": msotc_vals, "md": arr[:-1]}
df = pd.DataFrame(data=data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.