I was plotting ocean current data and had the following data:
longitude (array | shape -> (360,)): The array with longitude points
latitude (array | shape -> (140,)): The array with latitude points
U (2d-array | shape -> (140, 360)) : The array with x-component of current velocities
V (2d-array | shape -> (140, 360)) : The array with y-component of current velocities
The problem is that the longitude array goes from 0 degrees to 360 degrees. I converted it to -180 to 180 format using:
lon = (lon + 180) % 360 - 180
The array now goes from 0 to 180 and -180 to 180. Is there a way to sort lon such that it goes from -180 to 180 and manipulate U and V to refect these changes too!
It is probably better to combine those 4 arrays into a single array of tuples.
array = []
for long, lat, u, v in zip(longitude, latitude, U, V):
array.append((long, lat, u, v))
# notice the double brackets here, because we're creating a tuple
Then you can sort array according to longitude, while still keeping each tuple of corresponding values together.
array.sort(key=lambda tup: tup[0])
(Instead of using tuples, you could also create NamedTuple
s or your own custom class, so that you can access each value using a dot operation. It's a little less cryptic than tup[0]
, especially if you plan to use these values all over your codebase.)
from collections import namedtuple
DataPoint = namedtuple("DataPoint", "longitude latitude u v")
array = []
for long, lat, u, v in zip(longitude, latitude, U, V):
array.append(DataPoint(long, lat, u, v)
array.sort(key=lambda value: value.longitude)