1

I want to plot some data of wind speed and direction on a wind rose (polar rose plot), but it seems that the library I am using (windrose) doesn't like when you feed it a negative wind direction. Thus, I am trying to add 360 degrees to all the negative values, thinking that it should plot. I tried doing the method shown in this post, if else in a list comprehension, but I still have plenty of negative numbers in my array.

 wind_speed=np.sqrt(u**2+v**2)
 wind_dir_calc=np.arctan(v/u)
 wind_dir=np.degrees(wind_dir_calc)

 [x+360 if x<0 else x+0 for x in wind_dir]

 np.set_printoptions(threshold=np.inf)
 print(wind_dir)

Sample output:
 [-6.34019175  84.6607632  -58.73626831  55.40771131  73.87242417
 66.70543675  48.0127875   50.71059314  52.27500496  38.15722659
 37.50414236  48.14495746  -2.20259816  16.53483786  38.75162833
 19.0466243  -58.67130713 -63.00416161 -65.41842552 -74.96956948
-74.23281746 -68.36911316 -46.46880071 -83.26398879 -80.75388725...]
jpp
  • 159,742
  • 34
  • 281
  • 339
Eli Turasky
  • 981
  • 2
  • 11
  • 28

2 Answers2

2

As in many cases, using a boolean index mask for your array is the best solution, since it is faster and easier than a comprehension. This is vectorized and thus fast and most pythonic/numpy-style:

wind_dir[wind_dir < 0] += 360
JE_Muc
  • 5,403
  • 2
  • 26
  • 41
  • Huh? Why the hell did I get a downvote? My answer is correct AND was the first answer. I agree that jpp posted a more comprehensive answer and thus deserves to be marked as accepted, but a downvote is not ok. – JE_Muc Jun 26 '18 at 16:07
2

Your logic is sound. You just need to assign your list comprehension to a variable. A list comprehension is not an in-place operation. For example:

wind_dir = [x+360 if x<0 else x+0 for x in wind_dir]

However, since you are using NumPy arrays, I recommend you use an in-place vectorised operation:

wind_dir[wind_dir < 0] += 360

To create a new array, you can use numpy.where:

wind_dir = np.where(wind_dir < 0, wind_dir + 360, wind_dir)
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Why would you want to create a new array? This is a quite slow operation, especially for large arrays. – JE_Muc Jun 26 '18 at 15:54
  • @Scotty1-, I didn't claim you *should*. But it's an option for more complex tasks and a good idea for new users to see different approaches. Indeed, my answer says I recommend an in-place... – jpp Jun 26 '18 at 15:55
  • 1
    Ok, I agree on that. :) – JE_Muc Jun 26 '18 at 15:56