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

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

  •  
  •   qazwsxkevin · 2019-05-17 01:14:37 +08:00 · 8771 次点击
    这是一个创建于 1799 天前的主题,其中的信息可能已经有所发展或是发生改变。
    读入的 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 条回复    2019-05-17 10:28:45 +08:00
    Xs0ul
        1
    Xs0ul  
       2019-05-17 01:30:49 +08:00
    你后面的报错,要不是因为前面 drop 过了那一行已经没有了,就是
    1. 加了 inplace 返回值是 None,加了赋值等于把 PageDF 清空了
    2. index 从 0 开始,dfmaxrow 得减一
    3. 如果 index 不是自动生成而是从原始数据读取的,可能不是 0 到 n-1 这样的。df.drop(df.index[-1], axis=0)试试
    necomancer
        3
    necomancer  
       2019-05-17 01:32:25 +08:00
    df.drop(df.tail(n).index) 从尾部去掉 n 行
    df.dorp(df.head(n).index) 从头去掉 n 行
    可以加上 inplace=True 直接修改原 dataFrame,不过函数返回是 None
    necomancer
        4
    necomancer  
       2019-05-17 01:33:56 +08:00
    如果数据结构简单的话,是不是 df[:-1] 就行了...
    ec0
        5
    ec0  
       2019-05-17 10:28:45 +08:00
    PageDF = PageDF[:-1]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4062 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 05:17 · PVG 13:17 · LAX 22:17 · JFK 01:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.