如何控制genfromtxt读取指定的行? [英] How to control genfromtxt to read rows specified?

查看:313
本文介绍了如何控制genfromtxt读取指定的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

genfromtxt可以跳过页眉和页脚行,并指定要使用的列. 但是我该如何控制要读取多少行?

genfromtxt can skip header and footer lines and speicfy which columns to use. But how can I control how many lines to read?

有时txt文件可能包含几个具有不同形状的块. 例如,

Sometimes a txt file might contain several blocks with different shape. For example,

a=StringIO('''
1,2,3
1,2,3
2,3
2,3
''')
genfromtxt(a,delimiter=',',skip_header=1)

这将引发错误,

ValueError: Some errors were detected !
    Line #4 (got 2 columns instead of 3)
    Line #5 (got 2 columns instead of 3)

当然,我可以这样:

a=StringIO('''
1,2,3
1,2,3
2,3
2,3
''')
genfromtxt(a,delimiter=',',skip_header=1,skip_footer=2)

这很丑陋,因为我必须计算该块下的行数.

It's ugly as I have to calculate the number of rows under the block.

但是我希望类似

genfromtxt(a,delimiter=',',skip_header=1,nrows=2)

那会更清楚.

有人对此有个好主意吗?还是使用其他功能?

Anyone have a good idea about that? Or use other function?

此问题已在新版本的Numpy中被解决.

This question has been solved in new version of Numpy.

genfromtxt现在有了一个名为max_rows的新关键字,该关键字使您可以控制要读取的行数,请参见此处.

genfromtxt now have a new keywords named max_rows which allow one to control the number of lines to read, cf here.

推荐答案

您可以使用invalid_raise = False跳过读取缺少某些数据的行. 例如

You can use the invalid_raise = False to skip reading the lines that are missing some data. E.g.

b = np.genfromtxt(a, delimiter=',', invalid_raise=False)

这会给您一个警告,但不会引发异常.

This will give you a warning, but will not raise an exception.

这篇关于如何控制genfromtxt读取指定的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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