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

pandas 读取 csv 形成 dataframe,结果类型都是 object,怎么才能复原到原始的所需要数据类型呢?

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

    df = pd.read_csv('text.csv', dtype={'code':str,‘ Sector ’:str,‘ price ’:decimal ??} 其中有一列数据为金额,所以想用 decimal,但是总是出错,请教大神们,这个怎么处理? 还有一个 Sector 列中想保存不包含某个字符串的行(对应 excel 中的筛选动作),这个又有什么简单明了的方法呢? 谢谢。

    4 条回复    2017-11-20 15:19:14 +08:00
    chy373180
        1
    chy373180  
       2017-11-20 10:28:05 +08:00
    看下 dtype 的类型,你设的这几种都没有
    object -- 代表了字符串类型
    int -- 代表了整型
    float -- 代表了浮点数类型
    datetime -- 代表了时间类型
    bool -- 代表了布尔类型

    筛选
    df = df[df['Sector'] != str_a]

    自己多谷歌吧
    ipwx
        2
    ipwx  
       2017-11-20 10:33:13 +08:00
    多看文档。

    pandas 的 dtype 对应 NumPy 的 dtype。NumPy 的 dtype 有两大类,NumPy 的 C 扩展库提供的 value type,还有 Python 自身的对象类型。对于 value type,NumPy 有 C 扩展库保证运算速度。

    所以除了 1L 列出来的那些类型,其他都会变成 object。
    jahan
        3
    jahan  
    OP
       2017-11-20 14:15:16 +08:00
    @chy373180 非常感谢。df = df[df['Sector'] != str_a]是保留所有不是 str_a 的吧,所有不包含 str_a 的是不是应该 df[str_a not in df[‘ Sector ’]] ?
    @ipwx 文档的话,是 pandas 的文档吗?马上开始,
    python 太好用了简直。
    hjq98765
        4
    hjq98765  
       2017-11-20 15:19:14 +08:00
    可以把文件先读进来再试着转小数,看看这一列的 dtype 是不是 float
    df['price'] = pd.to_numeric(df['price'], errors='ignore')

    要是那一列的 dtype 还是 object,那就 df['price'].value_counts()一下看看到底是什么值不是数字

    ----------------------------------------

    也有一种可能,是 csv 文件里的数据都加了双引号,导致直接读成 float 报错
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3058 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:11 · PVG 22:11 · LAX 07:11 · JFK 10:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.