【问题标题】:Convert CSV Data Stream into Pandas DataFrame (Python 2.7)将 CSV 数据流转换为 Pandas DataFrame (Python 2.7)
【发布时间】:2017-11-14 11:36:04
【问题描述】:

我有一个名为 jobresults 的 CSV 数据流/对象:

"number","person1","person2","type"
1234,"Michael Scott","Pam Beasley",false
2345,"Michael Scott","Jim Halpert",true
3456,"Jim Halpert","Dwight Schrute",false

如何将此对象(它不写到文件中)转换为 Pandas DataFrame?

我试过了:

df = pd.read_csv(jobresults)

...无济于事。我相信read_csv 需要从操作系统中提取的实际文件。

任何见解将不胜感激!

【问题讨论】:

    标签: python python-2.7 csv pandas dataframe


    【解决方案1】:

    使用io.StringIO

    作为stated here

    对于 Python 3 使用

    from io import StringIO
    
    df = pd.read_csv(StringIO(jobresults))
    

    对于 Python 2 使用

    from StringIO import StringIO
    
    df = pd.read_csv(StringIO(jobresults))
    

    考虑到你的对象是splunklib.binding.ResponseReader 你可能需要使用read() 方法...

    试试这个:

    from StringIO import StringIO
    
    df = pd.read_csv(StringIO(jobresults.read()))
    

    【讨论】:

    • 我收到此错误:File "<ipython-input-39-64e491fd9bb9>", line 69, in <module> df = pd.read_csv(StringIO(jobresults)) TypeError: initial_value must be unicode or None, not ResponseReader 如果这很重要,我正在使用 Python 2.7。
    • 什么是type(jobresults)
    • splunklib.binding.ResponseReader - 它是来自 Splunk 查询的提要
    • 完美 - 非常感谢。为这个简单的问题道歉。
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2018-12-09
    • 2017-03-17
    • 2017-03-23
    • 2017-07-20
    • 2021-05-17
    相关资源
    最近更新 更多