Solved

Python iterate over two arrays at the same time

Posted on 2015-02-11
1
108 Views
Last Modified: 2015-02-19
Dear all,

I'm trying to write to CSV in the following format.

Latitude  Longitude  Date1 Date2 Date3 etc

I have written the header, then to write the subsequent rows I need to get the same index for lat and lon append to content array, then iterate through the indexes of the date array to find the right value for sfc and append to content array.

At the moment i'm iterating through the first lat, then all the lons.  I'm not sure how to keep track of both indexes of lat/lon.

Once one row of data has been stored correctly I will write to file i.e. outputwriter.writerow(content)

In order to build the content array below is an example of the indexes for a row of data
sfc[time_index, lat_index, lon_index]
sfc[1, 1, 1]
sfc[2, 1,1]
sfc[3, 1,1]

and repeat for the next lat/lon iterating through the dates

data = sfc[time_index, lat_index, lon_index]
sfc[1, 2, 2]
sfc[2, 2,2]
sfc[3, 2,2]


header = ['Latitude', 'Longitude']
with open('Output.csv', 'wb') as csvFile:
    outputwriter = csv.writer(csvFile, delimiter=',')
    for time_index, time in enumerate(times): # pull the dates out for the header
         t = num2date(time, units = units, calendar='365_day')
         header.append(t)
    outputwriter.writerow(header) 
    
    for lat_index, lat in enumerate(lats):
        content = [lat] # first value in row lat
        #print lat_index
        for lon_index, lon in enumerate(lons):
            content.append(lon) # second value in row lon
            for time_index, time in enumerate(times): 
                n = num2date(time, units = units, calendar='365_day') # debug purposes only print to console
                data = sfc[time_index,lat_index,lon_index]
                if data != "--":
                   content.append(data)
                   print "data at:", n, lat, lon
                   print time_index,lat_index,lon_index
                   print data

Open in new window


I'm unsure of a way to implement this in python, thanks
0
Comment
Question by:AndyC1000
1 Comment
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
ID: 40605094
It's tough to tell from the sample data that you posted what exactly you've got there.  It might make things a little more clear if you posted a small subset of your time, lats, lons, and sfc arrays-- not just indices-- and what you would like that subset translated to as far as CSV goes. But... here's a guess based on what you did post.  
from collections import defaultdict
lats = [10.5, 22.3, 94.6]
lons = [33.1, 44.6, 102.8]
times = ["1:00am", "1:30am", "2:00am", "2:30am"]
sfc = dict()
sfc[1,1,1] = ""
sfc[2,1,1] = ""
sfc[3,1,1] = ""

sfc[1,2,2] = ""
sfc[2,2,2] = ""
sfc[3,2,2] = ""

lat_lon_times = defaultdict(list)
for (time_index, lat_index, lon_index) in sfc.keys():
    lat_lon = (lats[lat_index], lons[lon_index])
    lat_lon_times[lat_lon].append(times[time_index])

for (k, v) in lat_lon_times.items():
    data = list(k)
    data.extend(sorted(v))
    print data

Open in new window

The above prints:
[22.3, 44.6, '1:30am', '2:00am', '2:30am']
[94.6, 102.8, '1:30am', '2:00am', '2:30am']

Open in new window

0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Less strange, but still introduction This introduction was added (1st August, 2011) to reflect some reactions.  Firstly, the term basics in the title of the article...  As any other word, it is a symbol with meaning attached to the word by some a…
Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now