重新调整数据形状,跳过特定数量的点

2024-09-24 00:31:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个1024^3的数据集要读取。但是这个数组太大了,所以我想每2^n个点保存一次数据。例如,如果我设置skip=2,那么数组将为512^3

import numpy as np
nx = 1024
filename = 'E:/AUTOIGNITION/Z1/Velocity1_inertHIT.bin'
U = np.fromfile(filename, dtype=np.float32, count=nx**3).reshape(nx, nx, nx)

如何使用“重塑”来实现这一点


Tags: 数据importnumpybinasnp数组filename
1条回答
网友
1楼 · 发布于 2024-09-24 00:31:28

如果我理解正确,您希望在3维中的每个维中对数组的每个(2^n):th值进行采样

您可以通过如下方式编制索引来实现这一点

>>> import numpy as np
>>> n = 1
>>> example_array = np.zeros((1024,1024,1024))
>>> N = 2^n
>>> example_array_sampled = example_array[::N, ::N, ::N]
>>> example_array_sampled.shape
(512, 512, 512)

验证其实际采样是否均匀:

>>> np.arange(64).reshape((4,4,4))[::2,::2,::2]
array([[[ 0,  2],
        [ 8, 10]],

       [[32, 34],
        [40, 42]]])

这段特定的代码仍然假设您将在索引到内存中之前读取整个数组。变量example_array_sampled将是原始数组的视图

有关索引numpy数组的详细信息:https://numpy.org/doc/stable/reference/arrays.indexing.html

有关numpy视图的一些信息:https://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html

相关问题(一维):subsampling every nth entry in a numpy array

相关问题 更多 >