marco
marco

Reputation: 899

convert numpy conditional to regular python 2.7 syntax

I went onto one line of code, which I want to convert from numpy syntax to regular python 2.7 syntax:

SunAz=SunAz + (SunAz < 0) * 360

source: https://github.com/Sandia-Labs/PVLIB_Python/blob/master/pvlib/pvl_ephemeris.py#L147

If we pretend that the numpy array is one dimensional, can it be translated to regular python 2.7 syntax like so:

newSunAz = []
for item in SunAz:
    if item < 0:
        newItem = item + item*360
        newSunAz.append(newItem)
    else:
        newSunAz.append(item)

??

Thank you for the help.

Upvotes: 0

Views: 65

Answers (2)

Paulo Scardine
Paulo Scardine

Reputation: 77329

Try this:

new_sun_az = [i+360 if i > 0 else i for i in sun_az]

The main difference is that most operators are applied to the list object in plain Python lists and return a single result, while they return a numpy array where each item is the result of the operation applied to the corresponding item on the original array for numpy arrays.

>>> import numpy as np
>>> plainlist = range(5)
>>> plainlist
[0, 1, 2, 3, 4]
>>> plainlist > 5   # single result
True
>>> nparray = np.array(plainlist)
>>> nparray
array([0, 1, 2, 3, 4])
>>> nparray > 5    # array of results
array([False, False, False, False, False], dtype=bool)
>>> 

[update]

Mike's answer is right. My original answer was:

new_sun_az = [i+i*360 if i > 0 else i for i in sun_az]

Upvotes: 2

Mike
Mike

Reputation: 7203

I'm not sure that this would be the translation. The line

SunAz=SunAz + (SunAz < 0) * 360

(SunAz < 0) creates a boolean array, True where the angle is negative, and false otherwise. Multiplying False by a constant gives 0, and True is interpreted to be a 1. This line actually says, "shift the angle by 360 degrees if negative, otherwise leave it be".

So a more literal translation would be the following:

SunAz = [angle + 360 if angle < 0 else angle for angle in SunAz]

Upvotes: 2

Related Questions