比较两个表并提取与这两个表相似的列

2024-09-28 20:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here嗨,我有两个数据矩阵,一个是A,另一个是B。我想比较A的第一行和B的第一行,如果在B中找到匹配项,那么应该提取B中的整列。在所附文件中,A、11、12、13和14也可以在B中找到。在这种情况下,B中11、12、13和14下的所有值都被提取到C中。换句话说,A是一个行向量,我想把它和B的第一行进行比较

我有下面的Matlab表达式,我想把它翻译成python:

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

谢谢


Tags: 文件数据imagehere表达式情况矩阵description
1条回答
网友
1楼 · 发布于 2024-09-28 20:19:17
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)

由此产生:

[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]

这段代码远没有经过优化,它只是向您展示实现结果的几个步骤

相关问题 更多 >