0

我正在尝试在 Jupyter 中绘制一个叶热图,但我收到错误 ValueError: Location values cannot contain NaNs, got: [nan, nan] 所以我需要从数组列表中删除被屏蔽的元素。我的数组如下所示:

Xpos
Out[68]: 
masked_array(
data=[[--, --, --, ..., --, --, --],
    [--, --, --, ..., --, --, --],
    [--, --, --, ..., --, --, --],
    ...,
    [-3.6872851848602295, -3.732004165649414, -3.7555367946624756,
     ..., --, --, --],
    [-3.819749116897583, -3.824702739715576, -3.804812431335449, ...,
     --, --, --],
    [-3.6894078254699707, -3.7181897163391113, -3.7022457122802734,
     ..., --, --, --]],
mask=[[ True,  True,  True, ...,  True,  True,  True],
    [ True,  True,  True, ...,  True,  True,  True],
    [ True,  True,  True, ...,  True,  True,  True],
    ...,
    [False, False, False, ...,  True,  True,  True],
    [False, False, False, ...,  True,  True,  True],
    [False, False, False, ...,  True,  True,  True]],
fill_value=9.96921e+36,
dtype=float32)

列表中的每个数组都有不同数量的被屏蔽元素,一些仅在末尾被屏蔽,另一些则完全被屏蔽。如何删除每个被屏蔽的元素?所以完全删除完全屏蔽的元素,只删除其他元素中的几个元素。这将导致数组具有不同长度的列表。

我的整个代码是:

#read in data:
matplotlib.use('Qt4Agg', warn=False)

def ncdump(nc_fid, verb=True):

 def print_ncattr(key):

     try:
         #print("\t\ttype:", repr(nc_fid.variables[key].dtype))
         for ncattr in nc_fid.variables[key].ncattrs():
             print('\t\t%s:' % ncattr,\
repr(nc_fid.variables[key].getncattr(ncattr)))
     except KeyError:
         print("\t\tWARNING: %s does not contain variable attributes" % key)

 # NetCDF global attributes
 nc_attrs = nc_fid.ncattrs()
 if verb:
     print("NetCDF Global Attributes:")
     for nc_attr in nc_attrs:
         print('\t%s:' % nc_attr, repr(nc_fid.getncattr(nc_attr)))
 nc_dims = [dim for dim in nc_fid.dimensions]  # list of nc dimensions
 # Dimension shape information.
 if verb:
     #print("NetCDF dimension information:")
     for dim in nc_dims:
         #print("\tName:", dim)
         #print("\t\tsize:", len(nc_fid.dimensions[dim]))
         print_ncattr(dim)
 # Variable information.
 nc_vars = [var for var in nc_fid.variables]  # list of nc variables
 if verb:
     print("NetCDF variable information:")
     for var in nc_vars:
         if var not in nc_dims:
             print('\tName:', var)
             print("\t\tdimensions:", nc_fid.variables[var].dimensions)
             print("\t\tsize:", nc_fid.variables[var].size)
             print_ncattr(var)
 return nc_attrs, nc_dims, nc_vars
 ###
results = nc.Dataset('H:/EMBC/Thesis/Python/NoS2,     Aa/201302cohNoS10001_1.tspar1.nc')#K

Longitude = results.variables['lon'][:]
Latitude = results.variables['lat'][:]
Time=results.variables['time'][:]
Xpos=results.variables['part_xpos'][:]
Ypos=results.variables['part_ypos'][:]
Trajectory=results.variables['trajectory'][:]


#%% Density
Density = np.tile(1,len(Ypos[0]))
print(len(Density),len(Ypos[0]),len(Xpos[0]))

#Create map
m = folium.Map([52.5, 2], zoom_start=5.5)
divvyStations =df = pd.DataFrame({'Xpos': Xpos[0], 'Ypos': 
Ypos[0],'Density': Density})

divvyStations.head()
OUT:
Density Xpos    Ypos
0   1   NaN NaN
1   1   NaN NaN
2   1   NaN NaN
3   1   NaN NaN
4   1   NaN NaN
#The first values are all NaN
#Now the part that gives me the error:
for index, row in divvyStations.iterrows():
    folium.CircleMarker([row['Ypos'],row['Xpos'] ],
                    radius=1,
                    #popup=row['Density'],
                    fill_color="#3db7e4", # divvy color
                   ).add_to(m)#, row['Density']

这给了我错误:

ValueError                                Traceback (most recent call last)
<ipython-input-3-2a47eaba6e43> in <module>()
  4                         radius=1,
  5                         #popup=row['Density'],
----> 6                         fill_color="#3db7e4", # divvy color
  7                        ).add_to(m)#, row['Density']
  8 m

D:\ProgramData\Anaconda3\lib\site-packages\folium\features.py in __init__(self, location, radius, popup, **kw)
    868     """
    869     def __init__(self, location, radius=10, popup=None, **kw):
--> 870         super(CircleMarker, self).__init__(location=location,         popup=popup)
    871         self._name = 'CircleMarker'
    872         options = _parse_path(**kw)

D:\ProgramData\Anaconda3\lib\site-packages\folium\map.py in __init__(self, location, popup, icon)
    645         # Must be _validate_coordinates b/c some markers are defined with
    646         # multiple coordinates values, like Polygons.
--> 647         self.location = _validate_coordinates(location)
    648         if icon is not None:
    649             self.add_child(icon)

D:\ProgramData\Anaconda3\lib\site-packages\folium\utilities.py in _validate_coordinates(coordinates)
     46     if _isnan(coordinates):
     47         raise ValueError('Location values cannot contain NaNs, '        ---> 48                          'got:\n{!r}'.format(coordinates))
     49     coordinates = _locations_tolist(coordinates)
     50     return coordinates

ValueError: Location values cannot contain NaNs, got:
[nan, nan]

所以我需要从 Xpos 和 Ypos 中删除我的 NaN(Ypos 类似于 Xpos)

我试过了:

任何帮助表示赞赏!

4

1 回答 1

0

我不可能重现列表错误...

import numpy as np
a = np.ma.masked_array([[0,0,0], [1,2,3],[4,5,6]], mask=[[True,True, True], [True,True, False],[False,False,True]])

a.compressed()

array([3, 4, 5])
于 2018-05-22T13:56:55.087 回答