我有一个txt数据文件,我只想从偶数行中加载。
有没有办法在不使用循环的情况下在 python 中做到这一点?
以下是我的数据文件的前 10 行:
1 25544U 98067A 98324.28472222 -.00003657 11563-4 00000+0 0 10
2 25544 51.5908 168.3788 0125362 86.4185 359.7454 16.05064833 05
1 25544U 98067A 98324.33235038 .11839616 11568-4 57349-2 0 28
2 25544 51.6173 168.1099 0123410 88.0187 273.4932 16.04971811 11
1 25544U 98067A 98324.45674522 -.00043259 11566-4 -18040-4 0 32
2 25544 51.5914 167.4317 0125858 91.3429 269.4598 16.05134416 30
1 25544U 98067A 98324.51913017 .00713053 11562-4 34316-3 0 48
2 25544 51.5959 167.1152 0123861 87.8179 273.5890 16.05002967 44
1 25544U 98067A 98324.51913017 .00713053 11562-4 34316-3 0 59
2 25544 51.5959 167.1152 0123861 87.8179 273.5890 16.05002967 44
一种方法是使用计数器和模运算符:
fname = 'load_even.txt'
data = [];
cnt = 1;
with open(fname, 'r') as infile:
for line in infile:
if cnt%2 == 0:
data.append(line)
cnt+=1
这将逐行读取文件,增加每行后的计数器cnt
,并仅在计数器值为偶数时才将该行附加到data
,在本例中对应于偶数行号。
对于numpy
数组的特定情况,您可以使用以下内容:
import numpy as np
fname = 'load_even.txt'
data = [];
cnt = 1;
with open(fname, 'r') as infile:
for line in infile:
if cnt%2 == 0:
data.append(line.split())
cnt+=1
data = np.asarray(data, dtype = float)
np.loadtxt() 没有跳过行的能力,除非它们是前 N 行。 否则,您将需要使用 np.genfromtxt():
with open(filename) as f:
iter = (line for line in f if is_even_line(line))
data = np.genfromtxt(iter)
其中 is_even_line() 是一个返回布尔值的函数,如果给定的行是偶数。在您的情况下,由于第一列指示该行是奇数还是偶数,因此 is_even_line() 可能如下所示:
def is_even_line(line):
return line[0] == '2'
以下是我最终的做法:
import numpy as np
import matplotlib.pyplot as plt
filename = 'zarya2000data.txt'
a = np.genfromtxt(filename)
evens = []
odds = []
N = 8 #30 #5826 #number of lines
for i in range(N): #2913*2
if np.mod(i,2) == 0:
evens.append(a[i,:])
else:
odds.append(a[i,:])
oddsArray = np.asarray(odds)
evensArray = np.asarray(evens)
print 'evensArray', evensArray
print''
print 'oddsArray', oddsArray
print ''