在python中,比较两个数组字符串值,如果没有,则在数组中添加值



我想比较两个数组(data_namesspecial的第0列(,如果它不在special,则添加该值data_sizedata_names的长度。

species = np.array([])
for i in range(data_size):
if not data_names[i,0] in species :
np.insert(species, str, data_names[i,0])

我尝试了很多方法,但作为,我总是出错

'<'在"type"one_answers"int"的实例之间不支持

你能帮我吗?我不知道该怎么办。感谢

我会这样做:

# create simple list
species = []
# iterate
for i in range(data_size):
# check name not in list
if data_names[i,0] not in species:
# add name to list
species.append(data_names[i,0])
# convert to numpy array
output = np.array(species)

insert方法的第二个参数可以是int、切片或int序列。它表示要插入元素的索引。您正在传递str关键字,该关键字在python中指的是字符串类型。所以翻译对此颇有怨言。此外,insert方法返回一个带有添加元素的新数组,但在您的代码片段中,您没有将此新元素分配给变量,因此结果不会产生影响。如果你想在第一个位置准备元素,你可以做:

for i in range(data_size):
if not data_names[i,0] in species :
species=np.insert(species, 0, data_names[i,0])

参考:https://numpy.org/doc/stable/reference/generated/numpy.insert.html

最新更新