【问题标题】:Faster way to move data from a vector to a 2d array in python?在python中将数据从向量移动到二维数组的更快方法?
【发布时间】:2021-08-22 14:36:27
【问题描述】:

这是我当前的代码:

#move data from vector, A, into 2D array, H
    for i in range(0,nlat):
        jmin = nheader+1+i*nlon
        jmax = nheader+(i+1)*nlon
        A = A[jmin:jmax+1]
        H[i] = A
        A = np.array(Alist)

我有一个很长的向量,我从中获取某些数据并将其放入维度为 nlat x nlon 的二维数组中。此设置有效,但非常耗时。任何关于如何加快速度或重写它的建议都会非常有帮助。

【问题讨论】:

  • np.reshape(A, (nlat, nlon))
  • 这能回答你的问题吗? Convert a 1D array to a 2D array in numpy
  • 不是真的,因为 len(A) != nlat*nlon。它不会以这种方式正确翻译。如果您可以通过代码判断,我将使用 A[5:10] 并将其放入 H[0],然后将 A[6:11] 放入 H[1] 等等。这需要一段时间,但不幸的是,重塑并不能满足我的需要。
  • 在您的示例中,nlatnlon 是什么? nheader 怎么样?如果此循环的目的是跳过标题,您可以简单地切片向量并 then 重塑。 A[nheader+1:].reshape((nlat, nlon))。您能否在问题中添加示例输入和输出以使其更清晰?
  • 这可能行得通。如果它不起作用,我会尝试并添加一个 MRE。谢谢

标签: python arrays


【解决方案1】:

您可以使用numpy

import numpy as np

vector = np.array(A).reshape(nlat, nlon)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    相关资源
    最近更新 更多