【发布时间】:2019-04-19 12:28:01
【问题描述】:
自从我一直在解决这个问题以来已经有 2 天了,但无法突破。在下面的代码中,内部 for 循环在每次运行时都会创建 pathwiseminS 一个 (252,) 数组。
我想要的是当这个循环结束时将它堆叠在另一个数组中(逐行或逐列,任何有效的东西!)。最后创建一个名为 total 的多维数组,它应该是 (200,252) 或 (252,200)。
我尝试过np.concatenate、'np.vstack 等,但无法做到这一点。
class pricing_lookback:
def __init__(self, spot, rate, sigma, time, sims, steps):
self.spot = spot
self.rate = rate
self.sigma = sigma
self.time = time
self.sims = sims
self.steps = steps
self.dt = self.time / self.steps
def call_floatingstrike(self):
simulationS = np.array([])
simulationSt = np.array([])
call2 = np.array([])
total = np.array([])
# total = np.empty(shape=[self.steps, self.sims])
# total = np.empty(shape=self.steps,).reshape(self.steps)
for j in range(self.sims):
sT = self.spot
pathwiseminS = np.array([])
for i in range(self.steps):
phi = np.random.normal()
sT *= np.exp(
(self.rate - 0.5 * self.sigma * self.sigma) * self.dt + self.sigma * phi * np.sqrt(self.dt))
pathwiseminS = np.append(pathwiseminS, sT)
total = pathwiseminS.copy()
# print(np.shape(pathwiseminS))
total = np.append([total],[total], axis=0)
# np.hstack((total,pathwiseminS.transpose()))
# print(np.size(b), np.shape(b))
call2 = np.append(call2, max(pathwiseminS[self.steps - 1] - self.spot, 0))
# print (pathwiseminS[self.steps-1])
# print(call2)
simulationSt = np.append(simulationSt, pathwiseminS[self.steps - 1])
simulationS = np.append(simulationS, min(pathwiseminS))
# print(b)
call = max(np.average(simulationSt) - np.average(simulationS), 0)
return call, total # ,call2,
如果我最后打印total,我会得到(2,252) 矩阵
【问题讨论】:
-
你为什么使用
np.append而不是列表追加?这样使用起来更快、更容易。 -
因为我不知道列表追加。我一直认为numpy数组更快
-
列表迭代更快,尤其是在构建新列表或数组时。 List append 只是添加一个指向列表的指针;它就地运行。
np.append是np.concatenate的覆盖函数,每次都会创建一个新数组(带有完整副本)。要获得正确的迭代连接,您必须密切关注维度。np.array([])的形状为(0,)。那只能与另一个一维数组连接。 -
np.empty(shape=[self.steps, self.sims])是一个(self.steps, self.sims)形状的数组,包含未指定的值。它不等同于empty列表[]。您可以将它与另一个具有共享维度的二维数组连接起来,但结果仍然具有那些未指定的值。
标签: arrays python-3.x numpy