12

I am unable to read data in Pandas: Input:

import pandas as pd

data = 'a,b,c\n1,2,3\n4,5,6'

pd.read_csv(StringIO(data),skipinitialspace=True)

Output:

NameError:name 'StringIO' is not defined

Please let me know why the error occurred and also let me know what to import.

smci
  • 32,567
  • 20
  • 113
  • 146
Abhishek
  • 515
  • 1
  • 5
  • 12
  • [Should we use pandas.compat.StringIO or Python 2/3 StringIO?](https://stackoverflow.com/questions/50283292/should-we-use-pandas-compat-stringio-or-python-2-3-stringio) – smci May 11 '18 at 01:00

4 Answers4

26

Found the solution here:

The error occurred because I didn't import StringIO. Unlike Python 2, in Python 3 you are required to import it.

from io import StringIO

After importing no error occurred. Output to the above question was:

   a b c
0  1 2 3
1  4 5 6

It can also be imported from pandas.compat which works for both Python 2 and 3.

from pandas.compat import StringIO
vvvvv
  • 25,404
  • 19
  • 49
  • 81
Abhishek
  • 515
  • 1
  • 5
  • 12
3

Try to add the below packages These packages should add this line at the beginning of your script.

import io
from io import StringIO
import string
import pandas as pd
from pandas.compat import StringIO
from collections import Counter

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

After adding the above packages I am not getting the below error

ModuleNotFoundError: No module named 'StringIO'
thrinadhn
  • 1,673
  • 22
  • 32
2

Its because it was removed in python 3 for a better module.

From What’s New In Python 3.0:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
Gabriel Fair
  • 4,081
  • 5
  • 33
  • 54
-1

StringIO needs to be imported as import StringIO before it can be used

EDIT: link for more information: https://docs.python.org/2/library/stringio.html