Azam
Azam

Reputation: 147

Save array data in one output file using for loop Python

I need someones opinion on how to extract and save the array data in one output file from this script. Files3 contain set number dataset files in Latitude, Longitude and Rainfall. Each dataset is arranged just like this:

Latitude    Longitude   Rainfall
-5.000    95.000     0.000
-4.900    95.000     0.000
-4.800    95.000     0.000
-4.700    95.000     0.000
-4.600    95.000     0.000

Objective : How to save all the dataset especially the rainfall and saved in file into this array. The problem is the output only picked up only one dataset.

Latitude  Longitude  Rainfall1  Rainfall2  Rainfall3 Rainfall4 . . 
   -5.000    95.000     0.000       0.000       0.000     0.000
   -4.900    95.000     5.7 0       0.000       0.000     23.9
   -4.800    95.000     0.000       10.4        0.000     0.000
   -4.700    95.000     0.000       0.000       0.000     0.000
   -4.600    95.000     0.000       0.000       0.000     0.000

The halfway script that I am using is just as follows:

import numpy as np
import matplotlib.pyplot as plt

files=np.loadtxt('files3',dtype=str)

for x in files:
    data=np.loadtxt(x)
    lat=data[:,0]
    lon=data[:,1]
    rain=data[:,2]
    rain=[lat,lon,rain]
    data1=np.array(rain)
    data1=data1.T
    np.savetxt( 'build-mean1.dat2',data1,fmt='%9.3f')

Upvotes: 1

Views: 2103

Answers (1)

Dlamini
Dlamini

Reputation: 285

The following works, I believe. Change the names of the files in my 'files3 declaration' to the names of your files, and the the number of files you like, or use glob.glob to automatically make them into a list called 'files3'. You can delete all of the print statements after you confirm the evolution of the array as data is added.

import numpy as np

files3 = ['brain-mean1.dat2','brain-mean2.dat2','brain-mean3.dat2']

for x in range(len(files3)):
    file = files3[x]
    data = np.loadtxt(file)
    lat = data[:,0]
    lon = data[:,1]
    rainR = data[:,2]
    rain = [lat,lon,rainR]
    rain = np.array(rain)
    print('new data')
    print(rain)
    print('rainfall only')
    print(rainR)
    if x==0:
        agRain = rain
        print(type(agRain))
    else:
        rainR = np.array(rainR)
        agRain = np.vstack((agRain, rainR))
    print('agRain')
    print(agRain)

data1 = agRain.T
print('data1')
print(data1)
np.savetxt('build-mean.dat2',data1,fmt='%9.3f')

Upvotes: 1

Related Questions