-2

enter image description hereHi I have two data matrix, one is A and the other is B. I want to compare the first row of A to that of B and if a match is found in B, then the whole column(s) in B should be extracted. In the attached file, under A, 11, 12, 13 and 14 can also be found in B. In this case all the values under 11, 12, 13 and 14 in B are extracted into C. In other words, A is a row vector and I want to compare it to the first row of B.

I have the following Matlab expression that works and I would like to translate it to python:

C = B(:,ismember(B(1,:),A))

Thanks!

Python1
  • 1
  • 2
  • Hi. Welcome to SO. Please show any effort and provide some code so we can help you. At the very least show the tables and expect results in a proper way. – Raphael Nov 09 '19 at 01:06
  • C = B(:,ismember(B(1,:),A)) I have this which works in matlab – Python1 Nov 09 '19 at 01:07
  • OK, can you provide two or more lines of A and B? – Raphael Nov 09 '19 at 01:12
  • Did you use numpy or list of lists to create the matrix? – Raphael Nov 09 '19 at 01:19
  • I am new to python. I tried attaching an image to show but it did not work. I used list of lists to create a matrix. A is a row vector and B is a 4 by 3 matrix. Some of the first row of A can be found in the first row of B. I want to compare the first row of A to that of B – Python1 Nov 09 '19 at 01:23
  • Search for numpy to create matrix, it's faster. I will try to provide an answer with list of lists anyway. – Raphael Nov 09 '19 at 01:24

1 Answers1

0
A = [[11, 12, 13, 14]]

B = [[11, 12, 13, 14, 15, 16],
     [2, 1.1, 1.1, 1.3, 1.4, 1.5],
     [2, 1.1, 1.1, 1.3, 1.4, 1.5],
     [2, 1.1, 1.1, 1.3, 1.4, 1.5],
     [2, 1.1, 1.1, 1.3, 1.4, 1.5]]

# Get difference between two lists.
diffs = set(A[0]).symmetric_difference(set(B[0]))


# Get the members index with list comprehension.
indexes = [B[0].index(diff) for diff in diffs]

# Copy B into C. Use copy() otherwise only the reference will be copied.
C = B.copy()

# Delete the columns of C
# This is slow but more readable since you are a beginner in python.
for row in C: 
    for index in indexes:
        del row[index]

    print(row)

Which Yields:

[11, 12, 13, 14]
[2, 1.1, 1.1, 1.3]
[2, 1.1, 1.1, 1.3]
[2, 1.1, 1.1, 1.3]
[2, 1.1, 1.1, 1.3]

This code is far from optimized, it's just to show you the several steps to achieve the result.

Raphael
  • 959
  • 7
  • 21