Python pandas NameError: StringIO is not defined

Abhishek picture Abhishek · May 30, 2016 · Viewed 34.1k times · Source

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.

Answer

Abhishek picture Abhishek · Feb 1, 2017

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