当存在变量空间分隔列时,在python(numpy)中加载数据集 [英] loading a dataset in python (numpy) when there are variable spaces delimiting columns

查看:141
本文介绍了当存在变量空间分隔列时,在python(numpy)中加载数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数字数据的大数据集,在它的某些行中有一些定界列的变量空间,例如:

I have a big dataset contains numeric data and in some of its rows there are variable spaces delimiting columns, like:

4 5 6
7  8    9
2 3 4

当我使用此行时:

dataset=numpy.loadtxt("dataset.txt", delimiter=" ")

我收到此错误:

ValueError: Wrong number of columns at line 2

如何更改代码以也忽略多个空格?

How can I change the code to ignore multiple spaces as well?

推荐答案

delimiter的默认值为任何空格".如果不使用loadtxt,它将处理多个空格.

The default for delimiter is 'any whitespace'. If you leave loadtxt out, it copes with multiple spaces.

>>> from io import StringIO
>>> dataset = StringIO('''\
... 4 5 6
... 7 8     9
... 2 3 4''')
>>> import numpy
>>> dataset_as_numpy = numpy.loadtxt(dataset)
>>> dataset_as_numpy
array([[ 4.,  5.,  6.],
       [ 7.,  8.,  9.],
       [ 2.,  3.,  4.]])

这篇关于当存在变量空间分隔列时,在python(numpy)中加载数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆