2016-03-15 31 views
0

我有一個代碼,我在這裏導入文本文件的內容並做一些繪圖。我的要求是,我想通過給出條件只導入那些行數據。在對導入的數據進行一些計算之後,我想要導入文本文件中剩餘的其餘行並進行進一步計算。這個過程完成後,我想分別將兩個計算組合成兩個數組。有條件地導入文本文件中的行

這是我有的示例代碼。我也上傳了文本文件到保管箱中。

import numpy as np 
from matplotlib import pyplot as plt 
from scipy.interpolate import RectBivariateSpline 
import numdifftools as nd 
plt.ioff() 

data5= np.loadtxt('textfile',skiprows=1,unpack = True).T 
ts3 = data5[:,1] ## Condition based on this data 
fillend= 37900 ## Read rows only till this value 
ft3 = data5[:,0] 
t3 = data5[:,2] 
Ek3 = data5[:,13] 
ek3 = data5[:,14] 
eko3 = data5[:,15] 
Eko3 = data5[:,16] 

## Initially I want to read only all the rows until ts3=37900 with the row corresponding to fillend also included 
## Until ts3 =37900, this is the calculation that I want to make 

e2 = interpolate.InterpolatedUnivariateSpline(t2,Ek2,k=5) ## Here length of Ek2 and t2 should be equal to 378) 

df2 =nd.Derivative(e2,method='central',n=1,order=2,full_output=False) 
e2 = (1-df2(t2)) 
df2 = df2(t2) 

## Beyond ts3 = 37900, i.e from 38000 onwards, this is the calculation that I want to make 
df2 =nd.Derivative(e2,method='central',n=1,order=2,full_output=False) 
e2 = (-df2(t2)) 
df2 = df2(t2) 

## At the end of the operation, I want to have only two arrays e2 and df2 with all the values calculated 

Sample file

+0

我也說不上來,一目瞭然,在此代碼什麼是工作,什麼是公正需要,和/或是否有錯誤。如果這是行得通的,那麼問題是什麼? – hpaulj

+0

@hpaulj我的目標是導入所有行,直到ts3 = 37900包括。然後我想要做一些計算,如上所示。計算完成後,我想導入其餘的行並進行第二次計算。在代碼中,這沒有實現。它只是要導入所有的行並進行計算。 –

+0

'loadtxt'逐行讀取文件,將結果收集到列表中。您可以執行相同的讀取。 'loadtxt'接受來自任何代碼的輸入。因此,您的文件讀取器可以逐行讀取文件,並將它們傳遞給'loadtxt',或退出。 – hpaulj

回答

1

這裏的加載TXT的一個簡單的例子(線)中兩個塊的基礎上,在所述線的值。我正在模擬一個帶有字符串列表的文件。 foo是一個生成器函數,它返回2個塊中的輸入。

import numpy as np 

t0 = '1, 2, 3, 4' 
t1 = '4, 5, 6, 7' 
txt=[t0,t0,t0,t1,t1,t1] 

def foo(txt): 
    lines = [] 
    while txt: 
     l = txt.pop(0) 
     if int(l.split(',')[1])<4: lines.append(l) 
     else: 
      yield lines 
      break 
    yield [l]+txt 

for lines in foo(txt[:]): 
    print(np.loadtxt(lines, delimiter=',')) 

結果是2個數組:

2033:~/mypy$ python stack36001473.py 
[[ 1. 2. 3. 4.] 
[ 1. 2. 3. 4.] 
[ 1. 2. 3. 4.]] 
[[ 4. 5. 6. 7.] 
[ 4. 5. 6. 7.] 
[ 4. 5. 6. 7.]] 
+0

謝謝你的回覆。我想我可能會對我的願望感到困惑。我有一個文本文件已經生成。導入文本文件後,我已將變量分配給不同的列。在此之後,我只想導入行直到ts3值= 37900.請查看附加的文本文件以獲得更好的想法。 –

+0

如果你把問題變成我的例子的大小,你可能會得到更多的幫助。 – hpaulj