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

请教使用 pandas 的正确姿势

  •  
  •   wisefree · 2017-11-13 20:08:10 +08:00 · 1789 次点击
    这是一个创建于 2349 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在用 apply 时,困惑了很久,>_<

    '''
    数据来源 monogodb,用 pymongo 连接,读取数据
    
    如果数据较少时,运行没有问题
    但是有 20 多万条数据时,有了问题
    
    some_col 的类型为 object
    
    '''
    
    def adjust_len(x, vaild_len):
        
        if x == '':
            return None
        elif len(x) > vaild_len:
            return 'other'
        else:
            return x
            
    
    df['some_col'].apply(adjust_len, args=(100,))
    
    '''
    TypeError: object of type 'int' has no len()
    '''
    
    

    为了找到原因

    
    def adjust_len(x, vaild_len):
        print(type(x), x)
        
        if x == '':
            return None
        elif len(x) > vaild_len:
            return 'other'
        else:
            return x
            
    
    df['some_col'].apply(adjust_len, args=(10,))
    
    
    '''
    <class 'str'> 5909229
    <class 'str'> 2574
    <class 'str'> 
    <class 'int'> 6227524
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-18-7b24ad6a1005> in <module>()
    '''
    
    

    <class 'int'> 6227524,怎么就突然变成了 int

    # 解决方案 1
    df['some_col'].astype(str).apply(adjust_len, args=(10,))
    
    #做一下转换,就可以了,但是为什么???
    
    wisefree
        1
    wisefree  
    OP
       2017-11-13 22:59:11 +08:00
    都是使用 df['some_col'].apply(adjust_len, args=(100,))

    df['some_col'].apply(adjust_len, args=(10,)),手滑了一下,-_-
    wisefree
        2
    wisefree  
    OP
       2017-11-13 23:09:49 +08:00
    结题哈,十分抱歉。

    我从未怀疑是数据源的问题,以为 mongodb 中存储的就是 string,谁知道存储的居然是 int
    刚刚用$type 检验了一下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   895 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:15 · PVG 05:15 · LAX 14:15 · JFK 17:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.