【发布时间】:2021-10-30 12:54:05
【问题描述】:
例如,给定矩阵
array([[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[ 0, 1, 2, 3, 4, 5],
[24, 25, 26, 27, 28, 29]])
并且 top_n=3,它应该返回
array([[24, 25, 26, 27, 28, 29],
[18, 19, 20, 21, 22, 23],
[12, 13, 14, 15, 16, 17]])
在给定输入二维矩阵 arr 的情况下,此函数应返回形状为 (top_n, arr.shape[-1]) 的 np.ndarray。
这是我尝试过的:
def select_rows(arr, top_n):
"""
This function selects the top_n rows that have the largest sum of entries
"""
sel_rows = np.argsort(-arr,axis=1)[:top_n]
return sel_rows
我也试过了:
sel_rows = (-arr).argsort(axis=-1)[:, :top_n]
无济于事。
【问题讨论】:
-
使用
-将数组转换为负数比在最后对数据进行切片效率低。对于小样本,这不是问题,但是在大数组中将所有值转换为负数会稍微慢一些,这通过%%timeit测试进行了验证。
标签: python arrays numpy indexing