python - 将 numpy recarray 复制到 ndarray
问题描述
我有一个过程需要将数据从 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 的东西。谢谢。
解决方案
这是未来的警告,而不是错误。更改已推迟到 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
无法正常工作。有一些关于抵消的复杂业务。
推荐阅读
- etw - 是否可以在 PerfMon 中查看使用 EventSource 在 C# 中引发的自定义 ETW 事件?实时?
- html - 导航栏中“溢出:隐藏”的含义
- python - numpy.argmax 的使用
- elasticsearch - fluentd 基于包含字符串的日志重新标记事件
- crystal-reports - 满足参数时如何在水晶报表中添加图像
- java - 使用 jaudiotagger 编写自定义(用户定义的)MP4 字段
- bash - 删除特定日期后的所有行
- heroku - 在 Heroku 上附加多个名称时如何删除插件?
- sql - pyspark.sql.utils.ParseException: u"\nextraneous > 输入 'xxx' 期待 {')', ','}
- redirect - 将用户从 www.mysite 重定向到 mysite