【问题标题】:python panda read_table does not existpython panda read_table不存在
【发布时间】:2015-04-08 05:01:16
【问题描述】:

我有一个数据框的字符串 s。

s='185662748,9359839,155872098,13.99,72\r\n185662748,9359839,155872098,15.58,75\r\n185662748,9359839,155872098,126.99,94\r\n'

我用过这个df=pd.read_table(s,sep=',',lineterminator='\n',header=header).

但它返回我

"IOError: 文件 185662748,9359839,155872098,13.99,72 ....不存在”

我想尽可能直接地将 sting 转换为如下输出:

a     b          c       d          e

0  185662748  9359839  155872098   13.99  72

1  185662748  9359839  155872098   15.58  75

2  185662748  9359839  155872098  126.99  94

【问题讨论】:

    标签: python string pandas dataframe


    【解决方案1】:

    read_table 需要文件名或类似文件的对象。如果你传递一个字符串,它期望它是一个文件名。您可以将字符串包装在 StringIO 对象中,使其表现得像文件一样,从而允许您 直接使用字符串:

    import pandas as pd
    from StringIO import StringIO
    
    s='185662748,9359839,155872098,13.99,72\r\n185662748,9359839,155872098,15.58,75\r\n185662748,9359839,155872098,126.99,94\r\n'
    
    pd.read_table(StringIO(s), sep=',', header=None)
    Out[10]: 
               0        1          2       3   4
    0  185662748  9359839  155872098   13.99  72
    1  185662748  9359839  155872098   15.58  75
    2  185662748  9359839  155872098  126.99  94
    

    【讨论】:

      【解决方案2】:

      是的。快速总结:

      1) 需要导入 StringIO。

      2) "header" 需要 int,来声明列位置

      3) "names" 声明列名。

      来源 2)、3):

      http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.io.parsers.read_table.html

      【讨论】:

        猜你喜欢
        • 2012-12-06
        • 2017-09-08
        • 1970-01-01
        • 2019-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-08
        • 1970-01-01
        相关资源
        最近更新 更多