首页 > 解决方案 > 在循环时附加一个二维数组

问题描述

我想将某些值存储在二维数组中。在下面的代码中。我想sT成为total。当内部循环运行要存储在行中的值时,然后在外部循环增量发生时存储在下一列中。

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.empty(shape=[self.steps, self.sims])
      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)
              np.append(total,[[j,sT]])###This should store values in rows of j column
              #print (pathwiseminS)
          #tst1 = np.append(tst1, pathwiseminS[1])
          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))
      call = max(np.average(simulationSt) - np.average(simulationS),0)
      return call, total#,call2, 

标签: pythonnumpymultidimensional-array

解决方案


这是我认为您正在尝试做的一个简单示例:

for i in range(5):
    row = np.random.rand(5,)
    if i == 0:
        my_array = row
    else:
        my_array = np.vstack((my_array, row))
    print(row)

但是,这对内存不是很有效,尤其是在处理大型数组时,因为这必须在每个循环上分配新内存。如果可能的话,最好预先分配一个空数组然后填充它。

要回答如何附加列的问题,应该是这样的:

import numpy as np

x = np.random.rand(5, 4)
column_to_append = np.random.rand(5,)
np.insert(x, x.shape[1], column_to_append, axis=1)

同样,这不是内存效率,应尽可能避免。预分配要好得多。


推荐阅读