【问题标题】:copy numpy recarray to ndarray将 numpy recarray 复制到 ndarray
【发布时间】:2018-10-06 03:53:37
【问题描述】:

我有一个过程需要将数据从 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]

我试过这个跳过第一个recarray到ndarray:

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的东西。 谢谢。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    这是未来的警告,而不是错误。更改已推迟到 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']] 的数据布局会有所不同,view 将不起作用。有一些关于抵消的复杂业务。

    【讨论】:

    • 谢谢。是的,最初我有 .copy() ......我想我今天早上忽略了这一点。那么,将值从 ndarray c_dot 复制回匹配 arr[['ID', 'X','Y','Z', 'FREQ']] 布局的任何提示?
    • 我不会担心在任何一个方向上逐个字段复制。您有 3 个字段,有多少条记录 - 1000 条? recfunctions 中的标准程序是逐字段复制。
    • 我可以轻松拥有 10e3 到 100e3 甚至 1e6 的记录,但性能并不是我首先关心的问题。我一直在寻找代码简单性,因为我必须对其他条目执行此操作。也就是说,我有一个工作程序,听起来很不错。我只需要每次都小心索引。感谢您的见解!
    • 最新的recfunctions已经结构化/非结构化函数。请参阅 1.16 文档
    猜你喜欢
    • 1970-01-01
    • 2018-08-04
    • 2019-04-07
    • 1970-01-01
    • 2018-10-10
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多