如何将值附加到多维numpy数组中

2024-06-16 12:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够在多维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"

Tags: numpynplistcatmonkeydogappendanimal
3条回答

试试这个:

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')

首先,定义list可能会引起很多问题,因为它是python的内置名称

第二,在这方面: animal = np.append(animal, list[i])i是{}的元素之一,不应将其用作索引

你不需要结婚,你似乎已经拥有了你所需要的

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

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)

相关问题 更多 >