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

pandas 如何删除最后一行(不确定索引号数和行数的情况下)?

  •  
  •   qazwsxkevin · May 17, 2019 · 9458 views
    This topic created in 2580 days ago, the information mentioned may be changed or developed.
    读入的 pd 不确定会有多少行,最后一行是没用的表格装饰,想删除,对 pandas 不熟,
    试着这样:

    PageDF = PageDF.append(pd.read_html(PageStr)[4], ignore_index=True)
    dfmaxrow = PageDF.shape[0]
    PageDF = PageDF.drop([21])
    # print(type(dfmaxrow))
    # PageDF = PageDF.drop(21, axis=0, inplace=True)
    # PageDF = PageDF.drop([21], axis=0, inplace=True)
    # PageDF = PageDF.drop([dfmaxrow],axis=0)
    PageDF.to_csv(savestblpath,encoding="utf_8_sig",header=None,index=0,float_format=None)

    注释的方式都是不行,第三行知道行号直接 drop 是没问题的。。。
    5 replies    2019-05-17 10:28:45 +08:00
    Xs0ul
        1
    Xs0ul  
       May 17, 2019
    你后面的报错,要不是因为前面 drop 过了那一行已经没有了,就是
    1. 加了 inplace 返回值是 None,加了赋值等于把 PageDF 清空了
    2. index 从 0 开始,dfmaxrow 得减一
    3. 如果 index 不是自动生成而是从原始数据读取的,可能不是 0 到 n-1 这样的。df.drop(df.index[-1], axis=0)试试
    necomancer
        3
    necomancer  
       May 17, 2019
    df.drop(df.tail(n).index) 从尾部去掉 n 行
    df.dorp(df.head(n).index) 从头去掉 n 行
    可以加上 inplace=True 直接修改原 dataFrame,不过函数返回是 None
    necomancer
        4
    necomancer  
       May 17, 2019
    如果数据结构简单的话,是不是 df[:-1] 就行了...
    ec0
        5
    ec0  
       May 17, 2019
    PageDF = PageDF[:-1]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1018 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 19:16 · PVG 03:16 · LAX 12:16 · JFK 15:16
    ♥ Do have faith in what you're doing.