【问题标题】:In python Compare two array string values and add the value in the array if not在python中比较两个数组字符串值,如果没有则将值添加到数组中
【发布时间】:2020-10-29 09:34:54
【问题描述】:

我想比较 2 个数组(data_namesspecies 的第 0 列)并添加不在 species 中的值。 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' 和 'int' 的实例之间不支持'

你能帮帮我吗,我不知道该怎么做。 谢谢

【问题讨论】:

    标签: python arrays python-3.x list compare


    【解决方案1】:

    我会这样做:

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

    【讨论】:

      【解决方案2】:

      insert 方法的第二个参数可以是整数、切片或整数序列。它表示您要插入元素的索引。您正在传递 str 关键字,它在 python 中是指字符串类型。所以翻译抱怨它。 此外,insert 方法返回一个新数组,其中包含您添加的元素,但在您的 sn-p 中,您没有将此新元素分配给变量,因此结果不会生效。 如果你想在第一个位置添加元素,你可以这样做:

      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

      【讨论】:

        猜你喜欢
        • 2021-12-07
        • 2018-05-04
        • 1970-01-01
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-17
        相关资源
        最近更新 更多