# 避免 Python DataFrame 中的 for 循环

[英]Avoid for loop in Python DataFrame

``````wealth = pd.Series(index = range(n+1))
wealth[0] = 100
for i in range(n):
wealth.iloc[i+1] = wealth.iloc[i]*(1+r.iloc[i]) - 6
``````

``````wealth = ((1 + r - 0.06).cumprod()).multiply(other = 100)
``````

``````r = returnY.sample(n,replace=True).reset_index(drop=True)
``````

``````yy = allWealth.copy()
yy[yy>0] = 1
yy[yy<=0] = 0
yy.sum(axis = 1)/N
``````

``````import numpy as np
from functools import reduce
rs = np.random.random(50)*0.3   #sequence of annual returns
result = reduce(lambda w,r: w*(1+r)-6, rs, 100)
``````

``````ts_iter= itertools.accumulate(rs, lambda w,r: w*(1+r)-6, initial=100)
ts = list(ts_iter)     #itertools.accumulate returns an iterable
``````

``````import numpy as np
rm = np.random.random((n,N))
def sim(rs):
return reduce(lambda w,r: w * (1+r) - 6, rs, 100)
result = np.apply_along_axis(sim, 0, rm)
``````

``````import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.random((50,30)))
``````

``````import numpy as np
import itertools

rm = np.random.random((n,N))   #sequence of annual returns
rm0 = np.insert(rm, 0, 100, axis=1)

def wealth(rs):
return list(itertools.accumulate(rs, lambda w,r: w*(1+r)-6))

result = np.apply_along_axis(wealth, 1, rm0)
``````

itertools.accumulate 不识别初始值。 因此在返回数组的前面插入了初始财富。