NumPy genfromtxt - 跳过以特定数字开头的行

时间:2016-02-23 09:52:27

标签: python numpy genfromtxt

我有一个文件,其中第一列有一个整数,告诉它是否是元数据的数据 - 以0开头的行是元数据,并且其中的列数不固定,而任何其他整数指定数据行:

   0  -1.0000E+02  2.0000E+03 -1.0000E+03  
   0   NDIM=   3   IPS =   1   
   1     3   0    0  1.8279163801E+001  2.1982510269E-002

我想使用numpy只能从以非零整数开头的行读取数据,我可以用numpy.genfromtxt()吗?

1 个答案:

答案 0 :(得分:1)

public class CustomSpringApplicationContextLoader extends SpringApplicationContextLoader { @Override protected SpringApplication getSpringApplication() { return new SpringApplicationBuilder().headless(false).build(); } } 可以接受迭代器作为其第一个参数。所以你可以构建一个生成器表达式来产生所需的行:

np.genfromtxt

然后

import re
lines = (line for line in open('data', 'rb')  if re.match(r'^\s*[1-9]', line) )

In [61]: np.genfromtxt(lines) Out[61]: array([ 1. , 3. , 0. , 0. , 18.2791638 , 0.02198251]) 测试行是否以空格开头,后跟1到9之间的数字。如果非零整数可以从0开始,那么你可以改为使用

re.match(r'^\s*[1-9]', line)