简体   繁体   中英

Compare two tables and extract the columns similar to both

enter image description here Hi 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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM