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

求助 Pandas DataFrame 只有单行遍历问题。

  •  
  •   kingmo888 · Jun 27, 2016 · 6722 views
    This topic created in 3640 days ago, the information mentioned may be changed or developed.

    有一个 DataFrame 有序数据,

    其 index 不是唯一性的(有的一个 key 对应 N 行,有的只有一行)。

    根据 index 选出某一条或多条数据,再强制转换为 pd.df 格式并推送数据到另外一个函数,

    另外一个函数中,循环遍历每一条数据。

    问题来了, 当 df 只有一条数据时,就自动转为 series 格式了,它就不再按照行遍历,而是按照 colums 遍历该行的每一个列了。

    而在这种时候,我依然想让他按行遍历一次。 请问咋处理?

    谢谢。

    5 replies    2016-06-27 10:23:51 +08:00
    billgreen1
        1
    billgreen1  
       Jun 27, 2016   ❤️ 1
    不管 index 对应一行还是多行,把它放入一个列表里面
    比如 index 是 5 ,对应只有一行
    你传入 df.loc[[index], :]这样返回的还是 DataFrame
    pming1
        2
    pming1  
       Jun 27, 2016
    同楼上的,再或者,就判断类型,如何是 series ,就直接读取,不遍历
    Perrie
        3
    Perrie  
       Jun 27, 2016
    df.ix[[index], ]
    注意 index 外面的括号
    这样取出就还是 df 格式

    不知道这是不是你需要的
    Perrie
        4
    Perrie  
       Jun 27, 2016
    啊, 1L 已经有了~~没错就是这样~
    kingmo888
        5
    kingmo888  
    OP
       Jun 27, 2016
    @billgreen1 @pming1 感谢感谢!

    我习惯用 ix (貌似是完全不如 loc 快),发现 index 上再加一个[]相当之关键!

    果然,好多事情体现在细节上。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4332 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 110ms · UTC 04:11 · PVG 12:11 · LAX 21:11 · JFK 00:11
    ♥ Do have faith in what you're doing.