python - 在循环时附加一个二维数组
问题描述
我想将某些值存储在二维数组中。在下面的代码中。我想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,
解决方案
这是我认为您正在尝试做的一个简单示例:
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)
同样,这不是内存效率,应尽可能避免。预分配要好得多。
推荐阅读
- c - 埃拉托色尼筛 - C 语言实现
- angular - 禁用 Chrome 自动填充(再次)70.0.3538.67
- python - 从大量图像(*.jpg)和标签(*.mat)制作张量流数据集
- spring - Spring - 尝试将新员工插入到 mySQL - 绑定参数 [1] 作为 [VARCHAR] - [null]
- java - 扩展非抽象 jpa 实体类
- javascript - 在 React 中打补丁后更新状态
- c# - 使用参数中的日期从 c# 调用存储过程
- amazon-s3 - Amazon S3 的端点是什么?
- ios - 如何根据 UITableViewCell 中的内容调整水平 UICollectionView 的高度
- r - 在 Azure Data Lake Analytics 中安装 R 包