Stack Overflow Asked by Eli Turasky on November 10, 2021
I have a netcdf file (data1
) that contains (latitude, longitude, time) and I want to pull out specific (latitude, longitude) points. To do this, I use a dictionary.
lats=[20,40]
lons=[-135,-75]
names=['jib', 'jibb']
d={}
for i in lats:
for j in lons:
for k in names:
d[k]=data1.sel(latitude=i).sel(longitude=j)
This is just an example where the data is meaningless. However, when I print out jib
and jibb
they have the same exact latitude and longitude. Why is this? What I want is for jib
to have lat=20 and lon=-135, while jibb
has lat=40 and lon=-75.
d['jib']
time: 44160
Coordinates:
longitude
()
float32
-75.0
latitude
()
float32
40.0
d['jibb']
time: 44160
Coordinates:
longitude
()
float32
-75.0
latitude
()
float32
40.0
Using zip()
you can create a generator that loops over all of your iterables simultaneously. When iterables are zipped a new iterable
is returned containing tuples of same-index values from each iterable
that was provided.
#Example Zip Return ~ based on your data
names = ['jib', 'jibb']
lats = [20,40]
lons = [-135,-75]
print(list(zip(names, lats lons))) #[('jib', 20, -135), ('jibb', 40, -75)]
When you use zip()
in a generator you are simply unpacking those tuples at each iteration.
#Solution:
d = {k:data1.sel(latitude=lt).sel(longitude=ln) for k, lt, ln in zip(names, lats, lons)}
notes:
zip()
have different lengths, the length of the iterable
returned from zip()
will be the same as the shortest iterable provided.
a = [1, 2, 3]
b = ['a', 'b']
print(list(zip(a, b))) #[(1, 'a'), (2, 'b')]
iterable
type.
a = (1, 2, 3)
b = ['a', 'b', 'c']
c = range(3)
print(list(zip(a, b, c))) #[(1, 'a', 0), (2, 'b', 1), (3, 'c', 2)]
Answered by Michael Guidry on November 10, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP