【问题标题】:Comparing by section two numpy arrays in python and displays the index column which is not the same在python中按部分比较两个numpy数组并显示不同的索引列
【发布时间】:2016-09-11 10:11:38
【问题描述】:

我想告诉你数组的索引列在哪里不一样。

import numpy as np
array1 = np.array(list(np.zeros(10))+list(np.ones(10)))
array2 = np.array(list(np.random.randint(2, size=10))+list(np.random.randint(2, size=10)))
matches = array1 == array2
section_sums = np.bincount(np.arange(matches.size)//10,matches)
att = int(section_sums[0])
att2 = int(section_sums[1])

print section_sums
print 'first  10 : '+ str(att)
print 'second 10 : '+ str(att2)

示例:

Array1:
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.  1.  1.  1.  1.  1.  1.  1.  1. 1. 1.]

Array2:
[ 0.  1.  0 . 1.  1.  1.  0.  1.  0.  1.  1.  1.  1.  0.  1.  0.  1.  1. 1. 0.]

我想要输出:

in section 1 index is not the same: 2,4,5,6,8,10
in section 2 index is not the same: 4,6,10

【问题讨论】:

    标签: python arrays python-2.7 numpy


    【解决方案1】:

    如果您将数组分成两部分,那么您可以比较它们。

    In [18]: a = np.array(np.split(a, [10]))
    
    In [19]: b = np.array(np.split(b, [10]))
    
    In [23]: ind, items = np.where(a != b)
    
    In [25]: items[ind==0] + 1
    Out[25]: array([ 2,  4,  5,  6,  8, 10])
    
    In [26]: items[ind==1] + 1
    Out[26]: array([ 4,  6, 10])
    

    【讨论】:

      【解决方案2】:

      这是一种方法-

      idx = np.flatnonzero(~matches)
      cut_idx = np.unique(idx//10,return_index=True)[1]
      out = np.split(np.mod(idx,10)+1,cut_idx)[1:]
      

      给定输入数组的示例运行 -

      In [182]: matches = array1 == array2
           ...: idx = np.flatnonzero(~matches)
           ...: cut_idx = np.unique(idx//10,return_index=True)[1]
           ...: out = np.split(np.mod(idx,10)+1,cut_idx)[1:]
           ...: 
      
      In [183]: out
      Out[183]: [array([ 2,  4,  5,  6,  8, 10]), array([ 4,  6, 10])]
      

      【讨论】:

      • 如何打印输出为:in section 1 index is not the same: 2,4,5,6,8,10in section 2 index is not the same: 4,6,10
      • @RiskaNanda 在打印命令中使用out[0]out[1]
      猜你喜欢
      • 2020-02-23
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多