通过删除一些符合条件的元素来清理二进制 numpy 数组

Cleaning a binary numpy array by removing some elements that fit a condition

我正在尝试将二进制文件加载到 numpy 并删除一些我不需要的不需要的值,然后重塑该数组并使用它进行一些计算。

这是我的代码供参考:

def read_binary_data(filename, buffer_size):

    np.set_printoptions(threshold=sys.maxsize)
    np.set_printoptions(formatter={'int': hex})

    with open(filename, "rb") as f:
        binary_array = np.fromfile(f, dtype='B', offset=3)

    print(binary_array)

结果如下:

 ...
 0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
 0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
 0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
 0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
 0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
 0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
 0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xcf 0xf4
 0xff 0xff 0x0 0x0 0x0 0x0]

比方说,我想单独删除所有出现的 0x4e 0x44 但不删除 0x4e0x44,这是我感兴趣的两者的组合. 因为如果说我有 0x4e 0x54 我想保持这个完整。

我怎样才能做到这一点?

感谢您的帮助

请注意,仅仅因为您的数组正在打印十六进制值,所以这些值本身仍然是整数。无论如何,这是一种查找和删除 0x4e 0x44 对的方法,但可能不是最有效的方法:

indices_to_delete = []

for i in range(len(binary_array) - 1):

    # Check if the current value and the one right after are a pair
    # If so, they will need to be deleted
    if binary_array[i] == int("0x4e", 0) and binary_array[i+1] == int("0x44", 0):
        indices_to_delete += [i, i+1]

binary_array = np.delete(binary_array[None, :], indices_to_delete, axis=1)[0]

您的二进制数组现在没有 0x4e 0x44 对,尽管 0x4e0x44 的任何单个实例都被单独留下。

谢谢大家的意见。

我找到了一种尽可能高效地实现这一目标的方法。可能有更好的方法来做到这一点,但现在这项工作 :D

    np.set_printoptions(formatter={'int': hex})
    with open(filename, "rb") as f:
        binary_array = np.fromfile(f, dtype='B')

    # Clean array
    to_remove = []
    indexes = np.where(binary_array == 0x4e)

    # find all occurences of 4E54
    x54_mask = binary_array[indexes[0] + 1] == 0x54
    to_remove = [*to_remove, *list(indexes[0][x54_mask])]

    # find all occurences of 4E53
    x53_mask = binary_array[indexes[0] + 1] == 0x53
    to_remove = [*to_remove, *list(indexes[0][x53_mask])]

    # removing unwanted values
    to_remove_f = []
    for i in to_remove:
        to_remove_f.append(i)
        to_remove_f.append(i + 1)

    binary_array = np.delete(binary_array, to_remove_f)

for 循环仅用于 'to_remove' 列表,该列表仅包含 < 10 个值。

和平:D