使用pandas从UCL网站读取波士顿数据时出错

时间:2016-07-30 22:02:13

标签: python python-2.7 csv pandas

任何帮助请从网址上阅读此文件。

eurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data'
data = pandas.read_csv(url, sep=',', header = None)

我尝试了sep =',',sep =';'和sep =' \ t'但数据读起来像这样 enter image description here

但是

data = pandas.read_csv(url, sep=' ', header = None)

我收到了错误,

 pandas/parser.pyx in pandas.parser.TextReader.read (pandas/parser.c:7988)()
 pandas/parser.pyx in pandas.parser.TextReader._read_low_memory (pandas/parser.c:8244)()
pandas/parser.pyx in pandas.parser.TextReader._read_rows (pandas/parser.c:8970)()
pandas/parser.pyx in pandas.parser.TextReader._tokenize_rows (pandas/parser.c:8838)()
pandas/parser.pyx in pandas.parser.raise_parser_error (pandas/parser.c:22649)()
CParserError: Error tokenizing data. C error: Expected 30 fields in line 2, saw 31

也许在这里提出同样的问题enter link description here但是接受的答案对我没有帮助。

任何帮助请从URL提供它来阅读此文件。

顺便说一下,我知道有波士顿= load_boston()来读取这些数据但是当我从这个函数中读取它时,属性“MEDV'在数据集中不会下载数据集。

1 个答案:

答案 0 :(得分:1)

有多个空格用作分隔符,这就是当您使用单个空格作为分隔符(sep=' '

时它无效的原因

您可以使用sep='\s+'

来完成
In [171]: data = pd.read_csv(url, sep='\s+', header = None)

In [172]: data.shape
Out[172]: (506, 14)

In [173]: data.head()
Out[173]:
        0     1     2   3      4      5     6       7   8      9     10      11    12    13
0  0.00632  18.0  2.31   0  0.538  6.575  65.2  4.0900   1  296.0  15.3  396.90  4.98  24.0
1  0.02731   0.0  7.07   0  0.469  6.421  78.9  4.9671   2  242.0  17.8  396.90  9.14  21.6
2  0.02729   0.0  7.07   0  0.469  7.185  61.1  4.9671   2  242.0  17.8  392.83  4.03  34.7
3  0.03237   0.0  2.18   0  0.458  6.998  45.8  6.0622   3  222.0  18.7  394.63  2.94  33.4
4  0.06905   0.0  2.18   0  0.458  7.147  54.2  6.0622   3  222.0  18.7  396.90  5.33  36.2

或使用delim_whitespace=True

In [174]: data = pd.read_csv(url, delim_whitespace=True, header = None)

In [175]: data.shape
Out[175]: (506, 14)

In [176]: data.head()
Out[176]:
        0     1     2   3      4      5     6       7   8      9     10      11    12    13
0  0.00632  18.0  2.31   0  0.538  6.575  65.2  4.0900   1  296.0  15.3  396.90  4.98  24.0
1  0.02731   0.0  7.07   0  0.469  6.421  78.9  4.9671   2  242.0  17.8  396.90  9.14  21.6
2  0.02729   0.0  7.07   0  0.469  7.185  61.1  4.9671   2  242.0  17.8  392.83  4.03  34.7
3  0.03237   0.0  2.18   0  0.458  6.998  45.8  6.0622   3  222.0  18.7  394.63  2.94  33.4
4  0.06905   0.0  2.18   0  0.458  7.147  54.2  6.0622   3  222.0  18.7  396.90  5.33  36.2