【问题标题】:Python, from matrix to arrayPython,从矩阵到数组
【发布时间】:2012-09-17 17:40:51
【问题描述】:

我有一个 3d 矩阵 grid_z0,其尺寸(假设)为 50x25x36。该矩阵的每个点代表一个单元格。我想将此矩阵转换为大小为 50x25x36 的一维数组。我还想创建 3 个相同大小的数组来显示单元格中心的坐标。 数组cx,cycz存储单元格中心在一个方向上的坐标。

这个例子可以工作,但速度很慢,尤其是对于大型数据集。有没有办法让它更快?

data={"x":[],"y":[],"z":[],"rho":[]}

for i in arange(0,50):
  for j in arange(0,25):
    for k in arange(0,36):
      data["x"].append(cx[i])
      data["y"].append(cy[j])
      data["z"].append(cz[k])
      data["f"].append(grid_z0[i][j][k])

【问题讨论】:

    标签: python


    【解决方案1】:

    您应该考虑使用NumPy

    >>> import numpy as np
    >>> a = np.random.rand(50,25,36) # Create a fake array
    >>> print a.shape
    (50, 25, 36)
    >>> a.shape = -1 # Flatten the array in place
    >>> print a.shape
    (45000,)
    

    扁平化你的数组时,你正在做相当于:

    >>> b = []
    >>> for i in range(a.shape[0]):
    ...     for j in range(a.shape[1]):
    ...         for k in range(a.shape[2]):
    ...             b.append(a[i,j,k])
    

    即先解析最后一个轴,再解析第二个,再解析第一个。

    给定三个长度为N 的一维列表cxcycz,您可以构造一个二维数组:

    >>> centers = np.array([cx,cy,cz])
    >>> print centers.shape
    (3, N)
    

    【讨论】:

    • 谢谢,但是重构矩阵的顺序是什么?例如 a[11][12][13] 的新数组中的索引是什么?
    【解决方案2】:

    使用Numpy 进行矩阵/数组操作。

    # convert to 1D array :
    grid_1d = np.asarray(grid_z0).ravel()
    

    对于第二个问题,您需要一个 3D 网格。见这里的例子: Numpy meshgrid in 3D

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2015-10-13
      • 2010-11-08
      • 1970-01-01
      • 2019-04-28
      相关资源
      最近更新 更多