pandas.read_csv来自字符串或程序包数据

t2a7ltrp  于 2023-02-20  发布在  其他
关注(0)|答案(2)|浏览(123)

我想使用read_csv读取一个包中的一些csv文本数据。

from pkgutil import get_data
from StringIO import StringIO

data = read_csv(StringIO(get_data('package.subpackage', 'path/to/data.csv')))

但是StringIO.StringIO在Python 3中消失了,io.StringIO只接受Unicode,有没有简单的方法可以做到这一点?

编辑:以下操作似乎不起作用

import pandas as pd

import pkgutil
from io import StringIO

def get_data_file(pkg, path):
    f = StringIO()
    contents = unicode(pkgutil.get_data('pymc.examples', 'data/wells.dat'))
    f.write(contents)
    return f

wells = get_data_file('pymc.examples', 'data/wells.dat')

data = pd.read_csv(wells, delimiter=' ', index_col='id',
                   dtype={'switch': np.int8})

失败于

File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 401, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 209, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 509, in __init__
    self._make_engine(self.engine)
  File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 611, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/usr/local/lib/python2.7/dist-packages/pandas/io/parsers.py", line 893, in __init__
    self._reader = _parser.TextReader(src, **kwds)
  File "parser.pyx", line 441, in pandas._parser.TextReader.__cinit__ (pandas/src/parser.c:3940)
  File "parser.pyx", line 551, in pandas._parser.TextReader._get_header (pandas/src/parser.c:5096)
pandas._parser.CParserError: Passed header=0 but only 0 lines in file
55ooxyrt

55ooxyrt1#

要将string传递给Pandasread_csv(),可以使用io.StringIO,例如:

import pandas as pd
from io import StringIO

df = pd.read_csv(StringIO("csv string"))
kse8i1jr

kse8i1jr2#

以下是我在3.3中使用的方法:

>>> import numpy as np, pandas as pd
>>> import io, pkgutil
>>> wells = pkgutil.get_data('pymc.examples', 'data/wells.dat')
>>> type(wells)
<class 'bytes'>
>>> df = pd.read_csv(io.BytesIO(wells), encoding='utf8', sep=" ", index_col="id", dtype={"switch": np.int8})
>>> df.head()
    switch  arsenic       dist  assoc  educ
id                                         
1        1     2.36  16.826000      0     0
2        1     0.71  47.321999      0     0
3        0     2.07  20.966999      0    10
4        1     1.15  21.486000      0    12
5        1     1.10  40.874001      1    14

[5 rows x 5 columns]

注意:我不得不手动将wells.dat放到那个位置,所以我不能保证我复制的正确,也不能保证结尾没有空格,因为我删除了一些。但是给read_csv传递一个BytesIO对象和一个编码参数应该可以。(实际上,你可能不用它,但这是一个好习惯。io.TextIOWrapper可能是另一种选择。)

相关问题