2017-04-23 7 views
6

समस्या के लिए आम पंक्तियों को कैसे हटाएं समस्या बहुत सरल है: मेरे पास दो 2 डी एनपी.एरे है और मैं एक तीसरी सरणी प्राप्त करना चाहता हूं जिसमें केवल पंक्तियां हों जो बाद के जुड़वां के साथ समान नहीं हैं।बेवकूफ: 2 मैट्रिस

उदाहरण के लिए

:

X = np.array([[0,1],[1,2],[4,5],[5,6],[8,9],[9,10]]) 
Y = np.array([[5,6],[9,10]]) 

Z = function(X,Y) 
Z = array([[0, 1], 
      [1, 2], 
      [4, 5], 
      [8, 9]]) 

मैं np.delete(X,Y,axis=0) लेकिन यह काम नहीं करता है की कोशिश की ...

उत्तर

2
Z = np.vstack(row for row in X if row not in Y) 
+0

सरल और सुरुचिपूर्ण! धन्यवाद – rugrag

+0

ध्यान दें कि इस समाधान के लिए दोनों सेटों के आकार के उत्पाद के बराबर कई संचालन की आवश्यकता है, जो कि आदर्श से बहुत दूर है। –

+0

@EelcoHoogendoorn, हो सकता है .. फिर भी यह 'Z = npi.difference (X, Y)' 'से लगभग 10 गुना तेज है। आप अपने आप से जांच सकते हैं :) – Luchko

0

यहाँ एक views आधारित दृष्टिकोण है -

# Based on http://stackoverflow.com/a/41417343/3293881 by @Eric 
def setdiff2d(a, b): 
    # check that casting to void will create equal size elements 
    assert a.shape[1:] == b.shape[1:] 
    assert a.dtype == b.dtype 

    # compute dtypes 
    void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:]))) 
    orig_dt = np.dtype((a.dtype, a.shape[1:])) 

    # convert to 1d void arrays 
    a = np.ascontiguousarray(a) 
    b = np.ascontiguousarray(b) 
    a_void = a.reshape(a.shape[0], -1).view(void_dt) 
    b_void = b.reshape(b.shape[0], -1).view(void_dt) 

    # Get indices in a that are also in b 
    return np.setdiff1d(a_void, b_void).view(orig_dt) 

नमूना रन -

In [81]: X 
Out[81]: 
array([[ 0, 1], 
     [ 1, 2], 
     [ 4, 5], 
     [ 5, 6], 
     [ 8, 9], 
     [ 9, 10]]) 

In [82]: Y 
Out[82]: 
array([[ 5, 6], 
     [ 9, 10]]) 

In [83]: setdiff2d(X,Y) 
Out[83]: 
array([[0, 1], 
     [1, 2], 
     [4, 5], 
     [8, 9]]) 
1

numpy_indexed पैकेज (अस्वीकरण: मैं उसके लेखक हूँ) अच्छा दक्षता के साथ, बहु-आयामी इस तरह के उपयोग के मामलों के लिए मानक numpy सरणी सेट संचालन लागू होता है:

import numpy_indexed as npi 
Z = npi.difference(X, Y) 
संबंधित मुद्दे