MAM*_*AMU 3 python numpy numpy-ndarray
我有一个大小为 268238 的字节数组。 (dtype="uint8") 如何将它们拆分为每个大小为 2211 的子数组?余数数组可以更小。
一般而言:出于某种原因,我尝试使用 numpy 将文件拆分为大小为 2211 字节的块。(附加信息:之后我想对数组中的所有这些 2211 个元素进行 base64_encode,但这仅用于您的附加信息)
# create an array to test the problem
import numpy as np
a = np.random.randint(255, size=268238).astype("uint8")
# check size and dtype.
a.size
a.dtype
# until now everything is fine
# now i want to split it in equal parts of 2211 elements
# last one may be smaller
#
https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html
# just take the elements size now...
(np.array_split(a, a.size // 2211))[0].size # <-- 2217... but why?
(np.array_split(a, a.size // 2211))[1].size # <-- 2217... but why?
# ...
(np.array_split(a, a.size // 2211))[120].size # <-- 2216 (remainder..)
Run Code Online (Sandbox Code Playgroud)
numpy.array_split方法有错误吗?
我预计每个块都是 2211 个元素(2211 个 uint8 数)。相反,我得到了 2217 个元素的块大小。如果我使用 119、120、121 或 122 作为array_split. 我仍然没有得到 2211 的块大小。
预先感谢您的帮助 :)
** 编辑:** 这是在做这项工作,但问题需要回答,为什么 array_split 的行为不符合预期。有人可以解释一下吗?
out = [a[i : i + 2211] for i in range(0, len(a), 2211)]
out[121].size
# 707 <-- the correct remainder
Run Code Online (Sandbox Code Playgroud)
该numpy的文件上array_split()说,强似每个片段的大小的array_split()功能,您还可以通过要发生分裂指数的选择。使用这个想法,下面的代码会给你你正在寻找的结果:
import numpy as np
a = np.random.randint(255, size=268238).astype("uint8")
split_positions = list(range(2211,268238,2211))
split_result = np.array_split(a, split_positions)
frag_size_list = [p.size for p in split_result]
print (frag_size_list)
Run Code Online (Sandbox Code Playgroud)
这个的输出是:
[2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 2211, 707]
Run Code Online (Sandbox Code Playgroud)
您的代码无法正常工作的原因与所涉及的算术有关。如果您尝试使用片段大小重新计算原始大小,您就会意识到这一点。
进一步详细说明为什么您的代码不起作用:
268238 / 2211 = 121.3198
268238 // 2211 = 121
Run Code Online (Sandbox Code Playgroud)
您将121作为片段数传递给array_split()函数。但这会产生2211您正在寻找的碎片大小吗?下面的算术说明它不会:
268238 / 121 = 2216.843(大约是2217)。