V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
LeeReamond
V2EX  ›  Python

numpy 对二维数组按某行或某列排序问题

  •  
  •   LeeReamond · 2022-03-03 18:55:44 +08:00 · 2172 次点击
    这是一个创建于 777 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需求:以某行或某列为 key ,对列或行顺序进行整体平移, 例如以下矩阵

    [[1.2, 0.5, 0.1, 0.9],
     [  3,   5,   8,   6]]
    

    如果以首行为 key ,期望获得结果为

    [[0.1, 0.5, 0.9, 1.2],
     [  8,   5,   6,   3]]
    

    使用代码是 np.argsort()

    import numpy as np
    d = np.array([[1.2,0.5,0.1,0.9],[3,5,8,6]], dtype=np.float32)
    print(d)
    print(d[0])
    print(np.argsort(d[0]))
    
    ### output:
    [[1.2 0.5 0.1 0.9]
     [3.  5.  8.  6. ]]
    [1.2 0.5 0.1 0.9]
    [2 1 3 0]
    

    其中 argsort 结果不正确,如果 argsort 输出结果是标号,那么应该输出[3,1,0,2]才对,印象里以前用 numpy 排序就是 argsort 搞的,这次知道为啥用不对了,有无大佬帮看一眼。

    另问一下逆序排序的办法,stackoverflow 上说用 np.fliplr()反转结果,感觉不太对啊

    3 条回复    2022-03-04 09:49:57 +08:00
    disk
        1
    disk  
       2022-03-03 19:32:09 +08:00   ❤️ 1
    重新排序,直接传入需要顺序的切片就行了。
    argsort 结果没问题,你搞错功能了,标号指定是元素下标不是排名号
    necomancer
        2
    necomancer  
       2022-03-04 02:20:17 +08:00
    1. 按行排列,用 argsort 以第一行排的话 a[:, np.argsort(a[0])]
    2. 按列排行,用 argsort 以第二列排的话 a[np.argsort(a.T[1]),:]
    3. 逆序排序好像挺反人类的,arr[::-1].sort() 会原位逆序排序(即 id(arr) 和先 arr[::-1].sort()再 id(arr) 会一样)。但如果用 argsort,得 np.argsort(a[0])[::-1]
    dongxiao
        3
    dongxiao  
       2022-03-04 09:49:57 +08:00
    ```
    d[:, d.argsort(axis=1)[0]]
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3613 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 10:32 · PVG 18:32 · LAX 03:32 · JFK 06:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.