user3447222
user3447222

Reputation: 1

Python - need to extract certain parts of an array

I have 2 lists: x_data , y_data

both are 86400 (x_data is time in hours) I want to be able to take out of my array the entries for x from 7 - 14 hours, and the corresponding values in y_data.

I've done

for i, j in enumerate(x_data):
        if ( j < 7 & j > 14): 
           print i, j

it doesn't work. I don't really know what to do. I have started trying to use python since this morning (trying to use it instead of IDL)

Upvotes: 0

Views: 1072

Answers (4)

Vatine
Vatine

Reputation: 21288

It would depend on exactly how the data is formatted.

You say you have 86400 elements, so I guess it's one element per second. If so, something like:

start = 7 * 3600 # 7 hours
end = 14 * 3600  # and 14 hours
x_slice = x_data[start:end]
y_slice = y_data[start:end]

This, however, requires that x_data is sorted in increasing time.

If that is not the case, you would have to do some looping over the two arrays in parallel (the zip-based method mentioned by jonrsharpe looks like a likely starting point).

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122154

The easiest way to do this is using zip:

for x, y in zip(x_data, y_data):
    if 7 < x < 14:
        print(x, y)

You can use a list comprehension to extract the values into a separate list:

extract = [(x, y) for x, y in zip(x_data, y_data) if 7 < x < 14]

With what you are doing:

for i, j in enumerate(x_data):

on each iteration, j is an element from x_data and i is its index. You can use this to access y_data:

     if 7 < j < 14:
         print(j, y_data[i])

but it is neater to zip the two lists together.

Upvotes: 2

nwalsh
nwalsh

Reputation: 471

In python, the operator is not & it is and

Upvotes: 0

venpa
venpa

Reputation: 4318

You do not need for loo to extract. Just do this:

print x_data[7:15]

There is no array in python. Python has list, you read more about list here.

Upvotes: 2

Related Questions