将列表写入数组并将其写入文件(Python)

时间:2012-09-19 12:36:14

标签: python numpy

我想这很容易,但我无法让它发挥作用。我有一个功能给我一个列表(1x128)。该函数位于循环内(1x32)。我想将函数中的所有列表(32x128)写入文件。这是代码:

count = 0  
savez =  np.zeros((waveforms.size/len(waveforms),len(waveforms)))

for wvf in waveforms:  # waveforms is an array of 132x128, so wvf is a list of 1x128 
   # some code
       ...
       ...
       ...

    z, maxpeak = get_first_peak(wvf)  #Function giving me z. z is a list of 128 numbers. 

    for index in range(len(z)):
     savez[count,index] = z[index]

     # Some more Code
       ...
       ...
       ...
    count = count + 1   
# Writing z to file
savetxt("logwvf.dat", savez, fmt="%7.1F") 

为什么这不给我一个包含所有32个z列表的文件?

编辑(如果我包含主要代码会有帮助吗?):

if __name__ == '__main__':

print '***********************************************'
print '      CORRECT CS L2 OFF-RANGE WAVEFORMS        '
print '***********************************************'

try:
    ifile  = sys.argv[1]
    ifile2 = sys.argv[2]
    ifile3 = sys.argv[3]
    ofile  = sys.argv[4]

except:
    print "Usage:", sys.argv[0], "ifile"; sys.exit(1)   

# Open and read file from std, and assign first four (orbit, time, lat, lon) columns to four lists, and last 128 columns (waveforms) to an array.

data = np.genfromtxt(ifile, delimiter = ',', dtype = 'float',
             converters = {i:remove_bracket for i in range(132)}
                 )


# Initiating data, the variables are view not copies of data.
orbit = data[:,0]
time  = data[:,1]
lat   = data[:,2]
lon   = data[:,3]
waveforms   = data[:,4:132]

#---------------------------------------------------------------    
# Constants
threshold_coef = 0.50
#---------------------------------------------------------------                
#Getting height of satellite (H_SAT)
count = 0
H_SAT = []

with open(ifile3, 'r') as hsatfile:
    for line in hsatfile:
       col = line.split()
       H_SAT.append(col[4])

#---------------------------------------------------------------
h_corr = [0]*len(waveforms)
#z=np.zeros((len(waveforms),((waveforms.size)/len(waveforms))))
savez = np.zeros((len(waveforms),(waveforms.size/len(waveforms))))
count = 0
#logwvffile=open('logwvf.dat', 'a')
#---------------------------------------------------------------
# Looping over all waveforms:
for wvf in waveforms:  
    print 'Waveform #: ', count+1
    # Getting waveform, log waveform and maxpeak value
    z, maxpeak = get_first_peak(wvf)

    for index in range(len(z)):
        savez[count,index] = z[index]

    print savez

#    savetxt("wvf.dat", wvf, fmt="%7.1F")

    # Max. of first peak 
    peaklogwvf = np.amax(z)

    # Finding the first peak of org. waveform:
    for i in range(len(z)):
        if (z[i]==peaklogwvf):
            gate_firstpeak = i

    firstpeak = wvf[gate_firstpeak]
    print 'First peak at: ', gate_firstpeak,',', firstpeak


    # Retracking gate of first peak
    print 'Using', threshold_coef*100,'% threshold retracker ...'

    Pn = thermalnoise_firstpeak(wvf)
    retrack_gate_first = threshold_retracker(wvf,Pn,threshold_coef,firstpeak)

    #---------------------------------------------------------------
    # Finding the gate of max. peak:
    for i in range(len(z)):
        if (wvf[i]==maxpeak):
            gate_maxpeak = i

    print ''
    print 'Maximum peak at: ', gate_maxpeak,',', maxpeak
        # Retracking gate of max peak
    if (gate_maxpeak-gate_firstpeak > 3):
        Pnmax = thermalnoise_maxpeak(wvf,gate_firstpeak,gate_maxpeak)
    else:
        Pnmax = Pn
        print 'Thermal noise (Max. peak): ', Pnmax

    retrack_gate_max = threshold_retracker(wvf,Pnmax,threshold_coef,maxpeak)


    # Peak 2 peak bin seperation
    peak2peak = retrack_gate_max-retrack_gate_first  

    print ''
    print 'Difference between retracking gates', peak2peak
    print ''

    if (peak2peak > 1 ):
        print 'Range needs to be corrected!'
        h_peak2peak = off_range_calc(peak2peak,float(H_SAT[count]))
    else:
        print 'Range ok, NO correction is needed!'
        h_peak2peak = 0.0

    print '***********************************************'
    print ''

    h_corr[count] =    h_peak2peak 
    count = count + 1   
#---------------------------------------------------------------    
#---------------------------------------------------------------
# Loop is closed
# Height is corrected
print 'The height corrections: ', h_corr
correct_height(ifile2,ofile,lat,h_corr)    


np.savetxt("logwvf.dat", savez, fmt="%7.1F")

编辑#2

哇,这很尴尬。我刚发现自己的错误。我在写入文件时只包含一位数字,当我需要至少3位时。

谢谢你们花时间帮助我。

1 个答案:

答案 0 :(得分:1)

您可能希望将(waveforms.size/len(waveforms),len(waveforms))设为基本列表savez,而不是创建[]零数组。

然后,当您循环waveforms时,只需附加新的z

savez.append(z)

完成后,只需将savez转换为数组(例如,使用savez=np.array(savez))并将后者用作np.savetxt的输入。

这样,您就不必将整个savez留在记忆中。

如果您希望始终将savez保留为数组,至少应考虑摆脱

for index in range(len(z)):
 savez[count,index] = z[index]

这是非常浪费的:你可以做一个savez[count][:] = z