StringIO is the file-like string buffer object we use when reading pandas dataframe from text, e.g. "How to create a Pandas DataFrame from a string?"
Which of these two imports should we use for StringIO (within pandas)? This is a long-running question that has never been resolved over four years.
StringIO.StringIO
(Python 2) / io.StringIO
(Python 3)
pandas.compat.StringIO
builtins, StringIO/cStringIO, BytesIO, cPickle, httplib
, iterator versions of range, filter, map and zip, plus other necessary elements for Python 3 compatibility - see the 0.13.0 whatsnew
Version 2/3 forking code for imports from standard (from EmilH):
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
# Note: but this is very much a poor-man's version of pandas.compat, which contains much much more
Note:
pandas.compat
has existed since pandas 0.13.0 (Jan 2014) as a subpackage within pandasI know this is an old question, but I followed breadcrumbs here, so perhaps still worth answering. It's not totally definitive, but current Pandas documentation suggests using the built in StringIO
rather than it's own internal methods.
For examples that use the
StringIO
class, make sure you import it withfrom io import StringIO
for Python 3.
FYI, as of pandas 0.25, StringIO
was removed from pandas.compat
(PR #25954), so you'll now see:
from pandas.compat import StringIO
ImportError: cannot import name 'StringIO' from 'pandas.compat'
This means the only answer is to import from the io
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With