?
Solved

Python iterate over two arrays at the same time

Posted on 2015-02-11
1
Medium Priority
?
139 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 25

Accepted Solution

by:
clockwatcher earned 2000 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
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 …

764 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