在 numpy 数组中追加函数

Append function in numpy array

我的项目需要帮助。我有一个像这样的数组?

rndm = [[0 1]
        [0 0]
        [0 0]
        [0 1]]

现在,我想将 par_1 = [[1 0]], par_2 = [[0 0], ch1 = [[1 1]], and ch2 = [[0 1]] 添加到 rndm。

我的代码如下所示:

new_rndm = []
new_rndm.append(par_1)
new_rndm.append(par_2)
new_rndm.append(ch1)
new_rndm.append(ch2)
# add them to rndm
rndm = numpy.append(rndm, [new_rndm])
print(rndm)

输出结果是这样的:

rndm = [0 1 0 0 0 0 0 1 1 0 0 0 1 1 0 1]

我期望的输出是:

rndm = [[0 1]
        [0 0]
        [0 0]
        [0 1]
        [1 0]
        [0 0]
        [1 1]
        [0 1]]

我认为问题是数组中不能使用append。如果正确,有人可以帮助我尝试其他什么功能吗?如果没有,请教育我。我非常愿意学习。谢谢!

您可以使用 .append 将一个数组添加到另一个数组的末尾。这里的问题是 numpy.append 首先展平数组,即。 numpy.append([1 0], [0 1])[1 0 0 1]。参见 the numpy docs on .append

使用np.append(<array>, <elem to append>, axis=0)

rndm = np.array([[0, 1],
        [0, 0],
        [0, 0],
        [0, 1]])

par_1 = [[1, 0]]; par_2 = [[0, 0]]; ch1 = [[1, 1]]; ch2 = [[0, 1]]

rndm = np.append(rndm, par_1, axis=0)
rndm = np.append(rndm, par_2, axis=0)
rndm = np.append(rndm, ch1, axis=0)
rndm = np.append(rndm, ch2, axis=0)

array([[0, 1],
       [0, 0],
       [0, 0],
       [0, 1],
       [1, 0],
       [0, 0],
       [1, 1],
       [0, 1]])

编辑:

整形:

x = np.array([2,1])
y = x.reshape(-1,1) # <------------ you have to do this
x.shape, y.shape

((2,), (2, 1))

您可以使用普通列表追加来生成所需的嵌套列表结构:

rndm = [[0, 1],
        [0, 0],
        [0, 0],
        [0, 1]
        ]

par_1 = [[1, 0]]
par_2 = [[0, 0]]
ch1 = [[1, 1]]
ch2 = [[0, 1]]

new_rndm = []

new_rndm.append(par_1)
new_rndm.append(par_2)
new_rndm.append(ch1)
new_rndm.append(ch2)

new_rndm = [i for k in new_rndm for i in k]

for data in new_rndm:
    rndm.append(data)

for data in rndm:
    print(data)

输出:

[0, 1]
[0, 0]
[0, 0]
[0, 1]
[1, 0]
[0, 0]
[1, 1]
[0, 1]