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
sunhk25
V2EX  ›  Python

numpy 二位数组过滤掉指定条件元素

  •  
  •   sunhk25 · 2019-12-10 13:45:55 +08:00 · 3491 次点击
    这是一个创建于 1571 天前的主题,其中的信息可能已经有所发展或是发生改变。
    • 如何过滤元素并保留二维数组
        t = np.asarray([[2,3,4],[1,2,3],[1,0,4],[4,5,6]])
        # 删除大于等于 4 的元素:保留二维数组但是不需要保留矩阵结构
        # 希望结果:[[4], [], [4], [4, 5, 6]]
    
        t[t >= 4]
        # 可以删除但是结果为一维
        # array([4, 4, 4, 5, 6])
    
        np.where(t >= 4, t, 0)
        # 不需要的元素( 0 )大量占用内存
        #array([[0, 0, 4],
        #       [0, 0, 0],
        #       [0, 0, 4],
        #       [4, 5, 6]])
    
    4 条回复    2019-12-11 15:48:53 +08:00
    epleone
        1
    epleone  
       2019-12-10 14:39:38 +08:00   ❤️ 1
    如果 a = [[4], [], [4], [4, 5, 6]], 那么 a.shape ?
    也许你需要稀疏矩阵,或者说说你这个需求是用来实现什么。
    CrazyRundong
        2
    CrazyRundong  
       2019-12-10 15:56:29 +08:00
    ```python
    from scipy.sparse import coo_matrix

    # ...

    t[t > 4] = 0
    coo_t = coo_matrix(t)
    ```

    稀疏矩阵和稠密矩阵有不同的存储方式。如果不知道矩阵的 pattern,那就用 corrdicate based index 存储吧
    CrazyRundong
        3
    CrazyRundong  
       2019-12-10 15:57:53 +08:00   ❤️ 1
    necomancer
        4
    necomancer  
       2019-12-11 15:48:53 +08:00
    用稀疏矩阵。稀疏矩阵 0 不占内存。操作基本和 numpy array 一致。你想要的结果只能用列表生成式了
    [_[_>=4] for _ in t]
    In [2]: [_[_>=4] for _ in t]
    Out[2]: [array([4]), array([], dtype=int64), array([4]), array([4, 5, 6])]

    In [3]: np.array([_[_>=4] for _ in t])
    Out[3]:
    array([array([4]), array([], dtype=int64), array([4]), array([4, 5, 6])],
    dtype=object)
    得到一个 object array
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5298 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 08:17 · PVG 16:17 · LAX 01:17 · JFK 04:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.