Python pandas NameError: StringIO is not defined

12

我无法读取Pandas中的数据: 输入:

import pandas as pd

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

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

输出:

NameError:name 'StringIO' is not defined

请告诉我错误的原因,并告诉我需要导入什么。


我们应该使用pandas.compat.StringIO还是Python 2/3 StringIO? - smci
4个回答

28

在这里找到了解决方案:

错误是因为我没有导入StringIO。与Python 2不同,在Python 3中,您需要导入它。

from io import StringIO

导入后没有出现错误。 对上述问题的输出是:

   a b c
0  1 2 3
1  4 5 6

它还可以从pandas.compat导入,可用于Python 2和3。

from pandas.compat import StringIO

4
在Python 2中,你还需要导入它,只是从一个不同的模块(也叫做StringIO)导入。 - user2357112

3

请尝试添加以下软件包。这些软件包应该在脚本的开头添加此行。

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

在添加了上述包之后,我不再遇到以下错误。
ModuleNotFoundError: No module named 'StringIO'

2
这是因为Python 3中移除了它,并提供了更好的模块。来自Python 3.0新特性
引用如下: “The StringIO和cStringIO模块已经被移除。取而代之的是导入io模块,并使用io.StringIO或io.BytesIO分别处理文本和数据。”
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接