Solved

Python iterate over two arrays at the same time

Posted on 2015-02-11
1
110 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
"instance has no attribute getitem" accessing python list item 3 47
Python - ImportError: No module named 'urllib2' 2 155
Python Regex Problem 24 125
How can I do this in Pyhton? 12 116
Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
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 …

895 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

11 Experts available now in Live!

Get 1:1 Help Now