Max*_*axU 6 python numpy pandas
我有以下方形DataFrame:
In [104]: d
Out[104]:
a b c d e
a inf 5.909091 8.636364 7.272727 4.454545
b 7.222222 inf 8.666667 7.666667 1.777778
c 15.833333 13.000000 inf 9.166667 14.666667
d 4.444444 3.833333 3.055556 inf 4.833333
e 24.500000 8.000000 44.000000 43.500000 inf
Run Code Online (Sandbox Code Playgroud)
这是修改的距离矩阵,表示对象['a','b','c','d','e']之间的成对距离,其中每行除以系数(权重),所有对角元素人为设置到np.inf.
如何以高效(矢量化)的方式获得如下所示的索引列表/向量:
d # index of minimal element in the column `a`
a # index of minimal element in the column `b` (excluding already found indices: [d])
b # index of minimal element in the column `c` (excluding already found indices: [d,a])
c # index of minimal element in the column `d` (excluding already found indices: [d,a,b])
Run Code Online (Sandbox Code Playgroud)
即在第一列中我们找到了索引d,所以当我们在第二列中搜索最小值时,我们将排除带索引的行d(先前在第一列中找到) - 这将是a.
当我们在第三列中寻找最小值时,我们将排除前面带有索引的行(['d','a']) - 这将是b.
当我们在第四列中寻找最小值时,我们将排除前面带有索引的行(['d','a','b']) - 这将是c.
我不需要diagonal(inf)元素,因此结果列表/向量将包含d.shape[0] - 1元素.
即结果列表将如下所示:['d','a','b','c']或者在Numpy解决方案的情况下,相应的数字索引:[3,0,1,2]
使用慢速for loop解决方案来解决这个问题不是问题,但是我无法绕过矢量化(快速)解决方案......
循环是我在这里看到的唯一解决方案。
但你可以使用numpy+numba来优化。
from numba import jit
@jit(nopython=True)
def get_min_lookback(A, res):
for i in range(A.shape[1]):
res[i] = np.argmin(A[:, i])
A[res[i], :] = np.inf
return res
arr = df.values
get_min_lookback(arr, np.zeros(arr.shape[1], dtype=int))
# array([3, 0, 1, 2, 0])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |