【问题标题】:How to append values into multidimensional numpy arrays如何将值附加到多维numpy数组中
【发布时间】:2021-08-21 21:05:20
【问题描述】:

我希望能够在多维 numpy 数组中附加值并访问所述值。

例如:

import numpy as np

animal = np.array([[]])

mammal = ["monkey","dog","cat"]
amphibian = ["frog","toad","salamanders"]
aquatic = ["fish","eel","whale"]

list = [mammal, amphibian, aquatic]

for i in list
   animal = np.append(animal, list[i])

animal = np.append(animal,bird[])
bird = np.append(bird,"eagle")

print(animal)
print(animal[2][2])

预期输出:

(["monkey","dog","cat"],
["frog","toad","salamanders"],
["fish","eel","whale"],
["eagle"])

"whale"

【问题讨论】:

  • 您应该考虑使用列表列表而不是 numpy 数组,因为您的行大小不完全相同。

标签: python arrays numpy for-loop multidimensional-array


【解决方案1】:

你不需要 numpy,你已经拥有了你需要的东西。

您可以将列表附加到列表列表中。

mammal = ["monkey","dog","cat"]
amphibian = ["frog","toad","salamanders"]
aquatic = ["fish","eel","whale"]

animal_list = [mammal, amphibian, aquatic]

animal_list.append(['eagle'])

print(animal_list)

print(animal_list[2][2])

打印

[['monkey', 'dog', 'cat'], ['frog', 'toad', 'salamanders'], ['fish', 'eel', 'whale'], ['eagle']]
whale

但是,您可以获取结果并将其转换为 numpy 数组

np_animal_list = np.array(animal_list)

【讨论】:

  • 跳过list_of_lists 创建。 animal_list.append(['eagle']) 应该可以。
【解决方案2】:

试试这个:

import numpy as np

animal = np.empty((0, 3), str)

mammal = ["monkey","dog","cat"]
amphibian = ["frog","toad","salamanders"]
aquatic = ["fish","eel","whale"]

x = [mammal, amphibian, aquatic]

for i in x:
    animal = np.append(animal, np.array([i]), axis=0)

print(animal)

输出:

array([['monkey', 'dog', 'cat'],
       ['frog', 'toad', 'salamanders'],
       ['fish', 'eel', 'whale']], dtype='<U11')

【讨论】:

    【解决方案3】:

    首先,定义list 可能会导致很多问题,因为它是一个python 内置名称。

    其次,在该行中: animal = np.append(animal, list[i]), ilist 的元素之一,不应用作索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-06
      • 2021-08-21
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2016-03-18
      • 1970-01-01
      相关资源
      最近更新 更多