Python pandas NameError: StringIO 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37530891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python pandas NameError: StringIO is not defined
提问by Abhishek
I am unable to read data in Pandas: Input:
我无法在 Pandas 中读取数据:输入:
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.
请让我知道发生错误的原因,并让我知道要导入的内容。
回答by Abhishek
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.
发生错误是因为我没有导入StringIO
. 与 Python 2 不同,在 Python 3 中您需要导入它。
from io import StringIO
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.
它也可以从中导入pandas.compat
,适用于 Python 2 和 3。
from pandas.compat import StringIO
回答by Gabriel Fair
Its because it was removed in python 3 for a better module.
这是因为它在 python 3 中被删除以获得更好的模块。
From What's New In Python 3.0:
The
StringIO
andcStringIO
modules are gone. Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.
在
StringIO
和cStringIO
模块都没有了。相反,导入io
模块并分别使用io.StringIO
或io.BytesIO
用于文本和数据。
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
回答by Thrindadh
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'
回答by Fred Cascarini
StringIO needs to be imported as import StringIO
before it can be used
StringIO 需要像import StringIO
以前一样导入才能使用
EDIT: link for more information: https://docs.python.org/2/library/stringio.html
编辑:更多信息的链接:https: //docs.python.org/2/library/stringio.html