【问题标题】:Fill an empty matrix and work with the rows in python [duplicate]填充一个空矩阵并使用python中的行[重复]
【发布时间】:2020-05-16 14:35:40
【问题描述】:

我有一个函数,用于计算形状为 1 x 250 的预测。我这样做 B 次。为了保存 B 运行的所有预测,我想逐行填充一个空的 B x 250 矩阵。哪种python方法最适合填充空矩阵,以便我可以以简单的方式访问行(例如将行相互减去)

一定有比下面更好的东西

indx = np.argsort(y_real[:,1])
print(len(indx)) #250

hat_y_b = []
for b in range(0,B):
      y_pred = function()
      hat_y_b = np.append(hat_y_b, y_pred[indx,1], axis=0)

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    我不确定我是否完全理解您的问题,但这里有一些关于处理 numpy 数组的一般提示:

    一般来说,将东西附加到 np 数组非常慢。相反,在开始时分配整个数组,并用数组索引填充:

    import numpy as np
    
    # first, make an array with 250 rows and B cols.
    # Each col will be a single prediction vector
    all_b_arr = np.zeros((250, B))
    
    # if no lower bound is specified, it is assumed to be 0
    for idx in range(B):
        # This array indexing means "every row (:), column idx"
        all_b_arr[:, idx] = function()
    

    【讨论】:

      猜你喜欢
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多