代码之家  ›  专栏  ›  技术社区  ›  kcw78

将numpy recarray复制到ndarray

  •  0
  • kcw78  · 技术社区  · 6 年前

    我有一个过程,需要将数据从numpy recarray提取到ndarray,然后在那里做一些向量计算(recarray来自pytables table.read()函数。)我想将数学输出(另一个ndarray)映射回原始recarray中的相同字段/列。我找到了一种方法一列一列地做。寻找一个更好的方式来来回与数据。我的代码:

    node_eigen_array = eigenvb_table.read_coordinates(node_rows)
    node_eigen_array.shape[0]
    10
    node_eigen_array.dtype
    dtype([('ID', '<i8'), ('X', '<f8'), ('Y', '<f8'), ('Z', '<f8'),  ('FREQ', '<i8')])
    resvec_array[:,0]=node_eigen_array['X']
    resvec_array[:,1]=node_eigen_array['Y']
    resvec_array[:,2]=node_eigen_array['Z']
    
    # do some stuff that returns ndarray c_dot...
    
    node_eigen_array['X']=cdot[:,0]
    node_eigen_array['Y']=cdot[:,1]
    node_eigen_array['Z']=cdot[:,2]
    

    resvec_array=node_eigen_array[['X','Y','Z']].view('float64').reshape((10,3))
    

    numpy抱怨:

    This code may break in numpy 1.13 because this will return a view instead of a copy -- see release notes for details.
    

    另外,寻找一些可以简化ndarray数据返回到recarray的东西。

    1 回复  |  直到 6 年前
        1
  •  1
  •   hpaulj    6 年前

    这是未来的警告,而不是错误。更改已推迟到1点16分。它与多字段索引有关,你的 [['X','Y','Z']] 步骤。

    In [56]: dt = np.dtype([('ID', '<i8'), ('X', '<f8'), ('Y', '<f8'), ('Z', '<f8'), ('FREQ', '<i8')])
    In [57]: arr = np.ones(3, dtype=dt)
    In [58]: arr       # a structured array, recarray is just variation
    Out[58]: 
    array([(1, 1., 1., 1., 1), (1, 1., 1., 1., 1), (1, 1., 1., 1., 1)],
          dtype=[('ID', '<i8'), ('X', '<f8'), ('Y', '<f8'), ('Z', '<f8'), ('FREQ', '<i8')])
    

    当你只看田野时,它是安静的:

    In [59]: arr[['X','Y','Z']]
    Out[59]: 
    array([(1., 1., 1.), (1., 1., 1.), (1., 1., 1.)],
          dtype=[('X', '<f8'), ('Y', '<f8'), ('Z', '<f8')])
    

    但是当你试图用它们做些什么的时候,它会发出改变的警告。注意,它仍然执行操作。

    In [60]: arr[['X','Y','Z']].view('float64')
    /usr/local/bin/ipython3:1: FutureWarning: Numpy has detected that you may be viewing or writing to an array returned by selecting multiple fields in a structured array. 
    
    This code may break in numpy 1.16 because this will return a view instead of a copy -- see release notes for details.
      #!/usr/bin/python3
    Out[60]: array([1., 1., 1., 1., 1., 1., 1., 1., 1.])
    

    消除警告的一种方法是添加 copy() 索引后:

    In [62]: arr[['X','Y','Z']].copy().view('float64')
    Out[62]: array([1., 1., 1., 1., 1., 1., 1., 1., 1.])
    

    view 换工作。但在计划的改变中 arr[['X','Y','Z']] 数据布局会有所不同 看法