numpy 将固定序列添加到数字数组的每一行

juud5qan  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(131)

我有以下循环:

comprehensive_merged_function = np.zeros(shape=(0, 1))

for i in range(256):
    comprehensive_merged_function = np.append(comprehensive_merged_function, utils.dec_to_bin(i, 8))

comprehensive_merged_function = np.array([list(s) for s in comprehensive_merged_function]).astype(int)

它为我提供了以下数组:

[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 1 0]
 ...
 [1 1 1 1 1 1 0 1]
 [1 1 1 1 1 1 1 0]
 [1 1 1 1 1 1 1 1]]

我想在256行中的每一行后面加上8倍(-1),以获得以下所需结果:

[[0 0 0 0 0 0 0 0 -1 -1 -1 -1 -1 -1 -1 -1]
     [0 0 0 0 0 0 0 1 -1 -1 -1 -1 -1 -1 -1 -1]
     [0 0 0 0 0 0 1 0 -1 -1 -1 -1 -1 -1 -1 -1]
     ...
     [1 1 1 1 1 1 0 1 -1 -1 -1 -1 -1 -1 -1 -1]
     [1 1 1 1 1 1 1 0 -1 -1 -1 -1 -1 -1 -1 -1]
     [1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1]]

我尝试了以下几种方法:

comprehensive_merged_function = np.zeros(shape=(0, 1))
appending_indexes = np.array([-1, -1, -1, -1, -1, -1, -1, -1])

for i in range(256):
    comprehensive_merged_function = np.append(comprehensive_merged_function, utils.dec_to_bin(i, 8))
    comprehensive_merged_function = np.row_stack(comprehensive_merged_function, appending_indexes)

comprehensive_merged_function = np.array([list(s) for s in comprehensive_merged_function]).astype(int)

我收到以下错误:

Traceback (most recent call last):
  File "compression comprehensive testing.py", line 262, in <module>
    comprehensive_merged_function = np.row_stack(comprehensive_merged_function, appending_indexes)
  File "<__array_function__ internals>", line 4, in vstack
TypeError: _vhstack_dispatcher() takes 1 positional argument but 2 were given

当然,我尝试了许多不同的方法来解决这个问题,但结果更糟,为了避免帖子超载,我没有在这里展示这些方法。
任何对我如何才能得到想要的结果的帮助都将不胜感激。

yqlxgs2m

yqlxgs2m1#

您可以使用np.hstack(arrays)组合两个数组。例如:

import numpy as np

a = np.arange(25).reshape(5, 5)
b = np.zeros((5, 4), dtype=int) - 1

np.hstack([a, b])

这将导致:

array([[ 0,  1,  2,  3,  4, -1, -1, -1, -1],
       [ 5,  6,  7,  8,  9, -1, -1, -1, -1],
       [10, 11, 12, 13, 14, -1, -1, -1, -1],
       [15, 16, 17, 18, 19, -1, -1, -1, -1],
       [20, 21, 22, 23, 24, -1, -1, -1, -1]])

您需要dtype=int,因为np.zeros()默认情况下提供浮点数,组合这些数组会将所有内容强制转换为浮点数。
在您的情况下,您可以这样做:

rows, cols = comprehensive_merged_function.shape
minus_ones = np.zeros((rows, 8), dtype=int) - 1
arr = np.hstack([comprehensive_merged_function, minus_ones])
wlsrxk51

wlsrxk512#

编辑-只是更改了一些内容,以便您的代码可以工作。复制这个,它应该会起作用
只需将这最后一行添加到您的代码中

comprehensive_merged_function = np.zeros(shape=(0, 1), dtype=int)

for i in range(256):
    comprehensive_merged_function = np.append(comprehensive_merged_function, utils.dec_to_bin(i, 8))

comprehensive_merged_function = np.c_[comprehensive_merged_function,np.full((256,8), -1)]

相关问题