推荐学习书目
› 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
cuibty
V2EX  ›  Python

pandas 如何按条件去重?

  •  
  •   cuibty · Feb 20, 2017 · 9794 views
    This topic created in 3504 days ago, the information mentioned may be changed or developed.
    数据如下:

    A | B
    -------------
    1 | 0.2
    -------------
    1 | 0.3
    -------------
    1 | 0.4
    -------------
    2 | 0.1
    -------------
    3 | 0.2
    -------------
    3 | 0.4


    按 A 列去重,保留 B 列中 最小的一行数据。
    4 replies  •  2017-02-21 09:37:40 +08:00
    raptium
        1
    raptium  
       Feb 20, 2017 via iPhone
    groupby min
    raptium
        2
    raptium  
       Feb 20, 2017 via iPhone
    或者 sort_values 然后 drop_duplicates
    kingmo888
        3
    kingmo888  
       Feb 21, 2017
    ```
    import pandas as pd
    data = [[1,1,1,2,3,3], [0.2,0.3,0.4,0.1,0.2,0.4]]
    data = pd.DataFrame(data)
    data = [[1,1,1,2,3,3], [0.2,0.3,0.4,0.1,0.2,0.4]]
    data = pd.DataFrame(data).T
    data.columns=['A', 'B']
    data.groupby('A').max()
    ```
    staticor
        4
    staticor  
       Feb 21, 2017   ❤️ 1
    推荐 groupby('A', as_index=False)['B'].min() 比较直接.


    另外也推荐看一看 pivot_table 函数, 更是强大.
    ```
    df.pivot_table(index='A', columns=None, values='B', aggfunc=min)
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2585 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 06:48 · PVG 14:48 · LAX 23:48 · JFK 02:48
    ♥ Do have faith in what you're doing.