2017-10-05 83 views
1

我有一個txt文件的數據,我只想從偶數行加載。np.loadtxt()如何從txt文件加載其他所有行? Python

有沒有辦法在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.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.8179 273.5890 16.05002967 44 
1 25544U 98067A 98324.51913017 .00713053 11562-4 34316-3 0 59 
2 25544 51.5959 167.1152.8179 273.5890 16.05002967 44 

回答

1

的np.loadtxt()不必跳過行的能力:

對於numpy陣列的特定情況下可以使用此操作。否則,你將要使用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' 
1

一種方式做到這一點是使用計數器和模運算符:

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,在這種情況下對應於偶數行號。除非它們是第一 N行

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) 
0

以下是我最後做它:

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 '' 
+0

如何簡單,就是:'evens = a [0 :: 2]'和'odds = a [1 :: 2]',這是正確的方法,也應該更快。 – jadsq