【问题标题】:Append function in numpy array在 numpy 数组中追加函数
【发布时间】:2020-09-23 11:44:13
【问题描述】:

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

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 不能在数组中使用。如果正确,任何人都可以帮助我尝试其他什么功能?如果没有,请教育我。我非常愿意学习。谢谢!

【问题讨论】:

  • 它是一个numpy数组吗?
  • @Sushanth rndm 是一个数组。
  • 我们可以看到它是一个数组,但它是 python nested list 还是 numpy array
  • @Sushanth 我的错,它是一个 numpy 数组

标签: python arrays python-3.x append add


【解决方案1】:

使用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))

【讨论】:

  • 您好!非常感谢您的回答!但是为什么我在尝试这个解决方案时会出错?错误是:ValueError:所有输入数组的维数必须相同,但索引 0 处的数组有 2 维,索引 1 处的数组有 1 维
  • 您使用什么numpy 版本?我用1.18.4
  • 您使用的是整个代码还是其中的一部分。因为我没有收到任何错误。
  • 我使用的是相同版本的 numpy。这只是我的代码的一部分。 rndm 和 par_1 等随机生成。
  • 这 (2, ) 是导致此问题的原因。将其重塑为 (2,1)
【解决方案2】:

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

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]

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 这是因为 rndm 是一个 numpy 数组。那么将其作为列表然后附加这些值会更好吗?
    • 之所以这样附加是因为这两个的形状是 (2,) 它们是扁平的,这就是为什么你只会得到这个答案,但如果你有这样的形状 (2,1) 那么你可以逐行追加。
    猜你喜欢
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 2016-04-08
    • 2015-02-21
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多