切换第二个矩阵的列索引,直到与第一个矩阵的最大匹配(二进制值)

2024-09-30 04:40:12 发布

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

起点:两个一个热编码数组

import numpy as np
import pandas as pd

arr1 = np.array([[1, 1, 0],
                 [0, 1, 0],
                 [0, 1, 1]])

arr2 = np.array([[0, 1, 0],
                 [0, 0, 1],
                 [1, 0, 1]])

匹配arr1和arr2:4/9

Aim:以多数数字匹配的方式切换arr2中的列,然后给出索引。


切换列0和1:

arr2b = np.array([[1, 0, 0],
                  [0, 0, 1],
                  [0, 1, 1]])

匹配arr1和arr2b:6/9


在arr2上使用所选列索引时的输出,例如借助数据帧:

col_idx = [1, 0, 2] # (column 0 and 1 are switched here)
pd.DataFrame(data=arr2).iloc[:,col_idx]

output

但这可能不是最好的结果。如何通过代码找到arr2的最佳列索引


Tags: importnumpypandas编码asnpcol数组
1条回答
网友
1楼 · 发布于 2024-09-30 04:40:12
from itertools import permutations
import numpy as np
import pandas as pd
    
arr1 = np.array([[1, 1, 0],
                 [0, 1, 0],
                 [0, 1, 1]])

arr2 = np.array([[0, 1, 0],
                 [0, 0, 1],
                 [1, 0, 1]])

切换列索引的所有排列如下所示:

prm = list(permutations(range(arr2.shape[1])))

是:[(0,1,2)、(0,2,1)、(1,0,2)、(1,2,0)、(2,0,1)、(2,1,0)]

我们循环所有这些排列,并检查命中了多少个数字:

matches = [(arr1==np.array(b[:,x])).sum() for x in prm]

is:[4,4,6,8,2,4]

prm_idx = np.argmax(matches)

is:3

best_col_idx = list(prm[prm_idx])

is:[1,2,0]

arr2[:,best_col_idx]

是:

array([[1, 0, 0],
       [0, 1, 0],
       [0, 1, 1]])

或在df中:

pd.DataFrame(data=arr2).iloc[:,best_col_idx]

enter image description here

检查:

(arr1==np.array(arr2[:,[1, 2, 0]]))

是:

array([[ True, False,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

因此,8xTrue是正确的,最大化列索引开关是正确的

相关问题 更多 >

    热门问题