GVKun编程网logo

Python numpy 模块-nanmin() 实例源码(python中numpy模块)

1

在本文中,您将会了解到关于Pythonnumpy模块-nanmin()实例源码的新资讯,同时我们还将为您解释python中numpy模块的相关在本文中,我们将带你探索Pythonnumpy模块-nan

在本文中,您将会了解到关于Python numpy 模块-nanmin() 实例源码的新资讯,同时我们还将为您解释python中numpy模块的相关在本文中,我们将带你探索Python numpy 模块-nanmin() 实例源码的奥秘,分析python中numpy模块的特点,并给出一些关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的实用技巧。

本文目录一览:

Python numpy 模块-nanmin() 实例源码(python中numpy模块)

Python numpy 模块-nanmin() 实例源码(python中numpy模块)

Python numpy 模块,nanmin() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.nanmin()

项目:AutoML5    作者:djajetic    | 项目源码 | 文件源码
  1. def normalize_array (solution, prediction):
  2. '''''' Use min and max of solution as scaling factors to normalize prediction,
  3. then threshold it to [0,1]. Binarize solution to {0,1}.
  4. This allows applying classification scores to all cases.
  5. In principle,this should not do anything to properly formatted
  6. classification inputs and outputs.''''''
  7. # Binarize solution
  8. sol=np.ravel(solution) # convert to 1-d array
  9. maxi = np.nanmax((filter(lambda x: x != float(''inf''), sol))) # Max except NaN and Inf
  10. mini = np.nanmin((filter(lambda x: x != float(''-inf''), sol))) # Mini except NaN and Inf
  11. if maxi == mini:
  12. print(''Warning,cannot normalize'')
  13. return [solution, prediction]
  14. diff = maxi - mini
  15. mid = (maxi + mini)/2.
  16. new_solution = np.copy(solution)
  17. new_solution[solution>=mid] = 1
  18. new_solution[solution<mid] = 0
  19. # normalize and threshold predictions (takes effect only if solution not in {0,1})
  20. new_prediction = (np.copy(prediction) - float(mini))/float(diff)
  21. new_prediction[new_prediction>1] = 1 # and if predictions exceed the bounds [0,1]
  22. new_prediction[new_prediction<0] = 0
  23. # Make probabilities smoother
  24. #new_prediction = np.power(new_prediction,(1./10))
  25. return [new_solution, new_prediction]
项目:AutoML4    作者:djajetic    | 项目源码 | 文件源码
  1. def normalize_array (solution, new_prediction]
项目:automl_gpu    作者:abhishekkrthakur    | 项目源码 | 文件源码
  1. def normalize_array (solution, new_prediction]
项目:AutoML-Challenge    作者:postech-mlg-exbrain    | 项目源码 | 文件源码
  1. def sanitize_array(array):
  2. """
  3. Replace NaN and Inf (there should not be any!)
  4. :param array:
  5. :return:
  6. """
  7. a = np.ravel(array)
  8. #maxi = np.nanmax((filter(lambda x: x != float(''inf''),a))
  9. # ) # Max except NaN and Inf
  10. #mini = np.nanmin((filter(lambda x: x != float(''-inf''),a))
  11. # ) # Mini except NaN and Inf
  12. maxi = np.nanmax(a[np.isfinite(a)])
  13. mini = np.nanmin(a[np.isfinite(a)])
  14. array[array == float(''inf'')] = maxi
  15. array[array == float(''-inf'')] = mini
  16. mid = (maxi + mini) / 2
  17. array[np.isnan(array)] = mid
  18. return array
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
  1. def min_max(self, mask=None):
  2. """Get the minimum and maximum value in this data.
  3.  
  4. If a mask is provided we get the min and max value within the given mask.
  5.  
  6. Infinities and NaN''s are ignored by this algorithm.
  7.  
  8. Args:
  9. mask (ndarray): the mask,we only include elements for which the mask > 0
  10.  
  11. Returns:
  12. tuple: (min,max) the minimum and maximum values
  13. """
  14. if mask is not None:
  15. roi = mdt.create_roi(self.data, mask)
  16. return np.nanmin(roi), np.nanmax(roi)
  17. return np.nanmin(self.data), np.nanmax(self.data)
项目:yt    作者:yt-project    | 项目源码 | 文件源码
  1. def test_extrema():
  2. for nprocs in [1, 2, 4, 8]:
  3. ds = fake_random_ds(16, nprocs = nprocs, fields = ("density",
  4. "veLocity_x", "veLocity_y", "veLocity_z"))
  5. for sp in [ds.sphere("c", (0.25, ''unitary'')), ds.r[0.5,:,:]]:
  6. mi, ma = sp.quantities["Extrema"]("density")
  7. assert_equal(mi, np.nanmin(sp["density"]))
  8. assert_equal(ma, np.nanmax(sp["density"]))
  9. dd = ds.all_data()
  10. mi, ma = dd.quantities["Extrema"]("density")
  11. assert_equal(mi, np.nanmin(dd["density"]))
  12. assert_equal(ma, np.nanmax(dd["density"]))
  13. sp = ds.sphere("max", ''unitary''))
  14. assert_equal(np.any(np.isnan(sp["radial_veLocity"])), False)
  15. mi, ma = dd.quantities["Extrema"]("radial_veLocity")
  16. assert_equal(mi, np.nanmin(dd["radial_veLocity"]))
  17. assert_equal(ma, np.nanmax(dd["radial_veLocity"]))
项目:vsi_common    作者:VisionSystemsInc    | 项目源码 | 文件源码
  1. def local_entropy(ocl_ctx, img, window_radius, num_bins=8):
  2. """ compute local entropy using a sliding window """
  3. mf = cl.mem_flags
  4. cl_queue = cl.CommandQueue(ocl_ctx)
  5. img_np = np.array(img).astype(np.float32)
  6. img_buf = cl.Buffer(ocl_ctx, mf.READ_ONLY | mf.copY_HOST_PTR, hostbuf=img_np)
  7. min_val = np.nanmin(img)
  8. max_val = np.nanmax(img)
  9. entropy = np.zeros_like(img,dtype=np.float32)
  10. dest_buf = cl.Buffer(ocl_ctx, mf.WRITE_ONLY, entropy.nbytes)
  11. cl_dir = os.path.dirname(__file__)
  12. cl_filename = cl_dir + ''/cl/local_entropy.cl''
  13. with open(cl_filename, ''r'') as fd:
  14. clstr = fd.read()
  15. prg = cl.Program(ocl_ctx, clstr).build()
  16. prg.local_entropy(cl_queue, entropy.shape, None,
  17. img_buf, dest_buf,
  18. np.int32(img.shape[1]), np.int32(img.shape[0]),
  19. np.int32(window_radius), np.int32(num_bins),
  20. np.float32(min_val), np.float32(max_val))
  21.  
  22. cl.enqueue_copy(cl_queue, entropy, dest_buf)
  23. cl_queue.finish()
  24.  
  25. return entropy
项目:scikit-gstat    作者:mmaelicke    | 项目源码 | 文件源码
  1. def minmax(X):
  2. """
  3. Returns the MinMax Semivariance of sample X.
  4. X has to be an even-length array of point pairs like: x1,x1+h,x2,x2+h,...,xn,xn+h.
  5.  
  6. :param X:
  7. :return:
  8. """
  9. _X = np.asarray(X)
  10.  
  11. if any([isinstance(_, list) or isinstance(_, np.ndarray) for _ in _X]):
  12. return [minmax(_) for _ in _X]
  13.  
  14. # check even
  15. if len(_X) % 2 > 0:
  16. raise ValueError(''The sample does not have an even length: {}''.format(_X))
  17.  
  18. return (np.nanmax(_X) - np.nanmin(_X)) / np.nanmean(_X)
项目:PyBloqs    作者:manahl    | 项目源码 | 文件源码
  1. def test_FmtHeatmap__get_min_max_from_selected_cell_values_with_cache():
  2. df_pn = df - 5.
  3. cache = {}
  4. fmt = pbtf.FmtHeatmap(cache=cache)
  5. res = fmt._get_min_max_from_selected_cell_values(None, df_pn)
  6. assert len(cache) == 1 and (None, None) in cache.keys()
  7. assert res == (np.nanmin(df_pn), np.nanmax(df_pn))
  8.  
  9. min_value, max_value = np.nanmin(df.loc[[''a''], [''aa'', ''bb'']]), np.nanmax(df.loc[[''a''], ''bb'']])
  10. res = fmt._get_min_max_from_selected_cell_values([''a''], ''bb''], df)
  11. assert len(cache) == 2 and (frozenset([''a'']), frozenset([''aa'', ''bb''])) in cache.keys()
  12. assert res == (min_value, max_value)
  13.  
  14. res = fmt._get_min_max_from_selected_cell_values([''a''], max_value)
项目:PyBloqs    作者:manahl    | 项目源码 | 文件源码
  1. def test_FmtHeatmap__get_min_max_from_selected_cell_values_without_cache():
  2. df_pn = df - 5.
  3. cache = None
  4. fmt = pbtf.FmtHeatmap(cache=cache)
  5. res = fmt._get_min_max_from_selected_cell_values(None, df_pn)
  6. assert cache is None
  7. assert res == (np.nanmin(df_pn), df)
  8. assert cache is None
  9. assert res == (min_value, max_value)
项目:Kinect-asus-xtion-Pro-Live-Calibration-Tutorials    作者:taochenshh    | 项目源码 | 文件源码
  1. def depth_callback(self,data):
  2. try:
  3. self.depth_image= self.br.imgmsg_to_cv2(data, desired_encoding="passthrough")
  4. except CvBridgeError as e:
  5. print(e)
  6. # print "depth"
  7.  
  8. depth_min = np.nanmin(self.depth_image)
  9. depth_max = np.nanmax(self.depth_image)
  10.  
  11.  
  12. depth_img = self.depth_image.copy()
  13. depth_img[np.isnan(self.depth_image)] = depth_min
  14. depth_img = ((depth_img - depth_min) / (depth_max - depth_min) * 255).astype(np.uint8)
  15. cv2.imshow("Depth Image", depth_img)
  16. cv2.waitKey(5)
  17. # stream = open("/home/chentao/depth_test.yaml","w")
  18. # data = {''img'':depth_img.tolist()}
  19. # yaml.dump(data,stream)
项目:Kinect-asus-xtion-Pro-Live-Calibration-Tutorials    作者:taochenshh    | 项目源码 | 文件源码
  1. def depth_callback(self,stream)
项目:Kinect-asus-xtion-Pro-Live-Calibration-Tutorials    作者:taochenshh    | 项目源码 | 文件源码
  1. def depth_callback(self, depth_img)
  2. cv2.waitKey(5)
项目:wrfxpy    作者:openwfm    | 项目源码 | 文件源码
  1. def basemap_raster_mercator(lon, lat, grid, cmin, cmax, cmap_name):
  2.  
  3. # longitude/latitude extent
  4. lons = (np.amin(lon), np.amax(lon))
  5. lats = (np.amin(lat), np.amax(lat))
  6.  
  7. # construct spherical mercator projection for region of interest
  8. m = Basemap(projection=''merc'',llcrnrlat=lats[0], urcrnrlat=lats[1],
  9. llcrnrlon=lons[0],urcrnrlon=lons[1])
  10.  
  11. #vmin,vmax = np.nanmin(grid),np.nanmax(grid)
  12. masked_grid = np.ma.array(grid,mask=np.isnan(grid))
  13. fig = plt.figure(frameon=False,figsize=(12,8),dpi=72)
  14. plt.axis(''off'')
  15. cmap = mpl.cm.get_cmap(cmap_name)
  16. m.pcolormesh(lon,lat,masked_grid,latlon=True,cmap=cmap,vmin=cmin,vmax=cmax)
  17.  
  18. str_io = StringIO.StringIO()
  19. plt.savefig(str_io,bBox_inches=''tight'',format=''png'',pad_inches=0,transparent=True)
  20. plt.close()
  21.  
  22. numpy_bounds = [ (lons[0],lats[0]),(lons[1],lats[1]),(lons[0],lats[1]) ]
  23. float_bounds = [ (float(x), float(y)) for x,y in numpy_bounds ]
  24. return str_io.getvalue(), float_bounds
项目:wrfxpy    作者:openwfm    | 项目源码 | 文件源码
  1. def basemap_barbs_mercator(u,v,lon):
  2.  
  3. # lon/lat extents
  4. lons = (np.amin(lon),np.nanmax(grid)
  5. fig = plt.figure(frameon=False,dpi=72*4)
  6. plt.axis(''off'')
  7. m.quiver(lon,u,latlon=True)
  8.  
  9. str_io = StringIO.StringIO()
  10. plt.savefig(str_io, float_bounds
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
  1. def setSymColormap(self):
  2. cmap = {''ticks'':
  3. [[0, (106, 0, 31, 255)],
  4. [.5, (255, 255,
  5. [1., (8, 54, 104, 255)]],
  6. ''mode'': ''rgb''}
  7. cmap = {''ticks'':
  8. [[0, (172, 56, 56)], (51, 53, 120)]],
  9. ''mode'': ''rgb''}
  10.  
  11. lvl_min = lvl_max = 0
  12. for plot in self.plots:
  13. plt_min = num.nanmin(plot.data)
  14. plt_max = num.nanmax(plot.data)
  15. lvl_max = lvl_max if plt_max < lvl_max else plt_max
  16. lvl_min = lvl_min if plt_min > lvl_min else plt_min
  17.  
  18. abs_range = max(abs(lvl_min), abs(lvl_max))
  19.  
  20. self.gradient.restoreState(cmap)
  21. self.setLevels(-abs_range, abs_range)
项目:kite    作者:pyrocko    | 项目源码 | 文件源码
  1. def setSymColormap(self):
  2. cmap = {''ticks'':
  3. [[0., (0,
  4. [1e-3,
  5. ''mode'': ''rgb''}
  6. cmap = {''ticks'':
  7. [[0., 0)],
  8. ''mode'': ''rgb''}
  9. lvl_min = num.nanmin(self._plot.data)
  10. lvl_max = num.nanmax(self._plot.data)
  11. abs_range = max(abs(lvl_min), abs_range)
项目:CHaMP_Metrics    作者:SouthForkResearch    | 项目源码 | 文件源码
  1. def setArray(self, incomingArray, copy=False):
  2. """
  3. You can use the self.array directly but if you want to copy from one array
  4. into a raster we suggest you do it this way
  5. :param incomingArray:
  6. :return:
  7. """
  8. masked = isinstance(self.array, np.ma.MaskedArray)
  9. if copy:
  10. if masked:
  11. self.array = np.ma.copy(incomingArray)
  12. else:
  13. self.array = np.ma.masked_invalid(incomingArray, copy=True)
  14. else:
  15. if masked:
  16. self.array = incomingArray
  17. else:
  18. self.array = np.ma.masked_invalid(incomingArray)
  19.  
  20. self.rows = self.array.shape[0]
  21. self.cols = self.array.shape[1]
  22. self.min = np.nanmin(self.array)
  23. self.max = np.nanmax(self.array)
项目:linearmodels    作者:bashtage    | 项目源码 | 文件源码
  1. def _choose_cov(self, cov_type, **cov_config):
  2. """Return covariance estimator reformat clusters"""
  3. cov_est = self._cov_estimators[cov_type]
  4. if cov_type != ''clustered'':
  5. return cov_est, cov_config
  6. cov_config_upd = {k: v for k, v in cov_config.items()}
  7.  
  8. clusters = cov_config.get(''clusters'', None)
  9. if clusters is not None:
  10. clusters = self.reformat_clusters(clusters).copy()
  11. cluster_max = np.nanmax(clusters.values3d, axis=1)
  12. delta = cluster_max - np.nanmin(clusters.values3d, axis=1)
  13. if np.any(delta != 0):
  14. raise ValueError(''clusters must not vary within an entity'')
  15.  
  16. index = clusters.panel.minor_axis
  17. reindex = clusters.entities
  18. clusters = pd.DataFrame(cluster_max.T, index=index, columns=clusters.vars)
  19. clusters = clusters.loc[reindex].astype(np.int64)
  20. cov_config_upd[''clusters''] = clusters
  21.  
  22. return cov_est, cov_config_upd
项目:faampy    作者:ncasuk    | 项目源码 | 文件源码
  1. def get_bBox(self):
  2. """
  3. Returns boundary Box for the coordinates. Useful for setting up
  4. the map extent for plotting on a map.
  5. :return tuple: corner coordinates (llcrnrlat,urcrnrlat,llcrnrlon,
  6. urcrnrlon)
  7. """
  8. x, y, z = zip(self)
  9. llcrnrlat = np.nanmin(y)
  10. urcrnrlat = np.nanmax(y)
  11. llcrnrlon = np.nanmin(x)
  12. urcrnrlon = np.nanmax(x)
  13. return (llcrnrlat,
  14. urcrnrlat,
  15. llcrnrlon,
  16. urcrnrlon)
项目:snetRenderer    作者:shubhtuls    | 项目源码 | 文件源码
  1. def visRenderedViews(self,outDir,nViews=0):
  2. pt = Imath.PixelType(Imath.PixelType.FLOAT)
  3. renders = sorted(glob.glob(outDir + ''/render_*.png''))
  4. if (nViews > 0) and (nViews < len(renders)):
  5. renders = [renders[ix] for ix in range(nViews)]
  6.  
  7. for render in renders:
  8. print render
  9. rgbIm = scipy.misc.imread(render)
  10. dMap = loadDepth(render.replace(''render_'',''depth_''))
  11. plt.figure(figsize=(12,6))
  12. plt.subplot(121)
  13. plt.imshow(rgbIm)
  14. dMap[dMap>=10] = np.nan
  15. plt.subplot(122)
  16. plt.imshow(dMap)
  17. print(np.nanmax(dMap),np.nanmin(dMap))
  18. plt.show()
项目:lotss-catalogue    作者:mhardcastle    | 项目源码 | 文件源码
  1. def find_bBox(t):
  2. # given a table t find the bounding Box of the ellipses for the regions
  3.  
  4. Boxes=[]
  5. for r in t:
  6. a=r[''Maj'']/scale
  7. b=r[''Min'']/scale
  8. th=(r[''PA'']+90)*np.pi/180.0
  9. dx=np.sqrt((a*np.cos(th))**2.0+(b*np.sin(th))**2.0)
  10. dy=np.sqrt((a*np.sin(th))**2.0+(b*np.cos(th))**2.0)
  11. Boxes.append([r[''RA'']-dx/np.cos(r[''DEC'']*np.pi/180.0),
  12. r[''RA'']+dx/np.cos(r[''DEC'']*np.pi/180.0),
  13. r[''DEC'']-dy, r[''DEC'']+dy])
  14.  
  15. Boxes=np.array(Boxes)
  16.  
  17. minra=np.nanmin(Boxes[:,0])
  18. maxra=np.nanmax(Boxes[:,1])
  19. mindec=np.nanmin(Boxes[:,2])
  20. maxdec=np.nanmax(Boxes[:,3])
  21.  
  22. ra=np.mean((minra,maxra))
  23. dec=np.mean((mindec,maxdec))
  24. size=1.2*3600.0*np.max((maxdec-mindec,(maxra-minra)*np.cos(dec*np.pi/180.0)))
  25. return ra,dec,size
项目:gripy    作者:giruenf    | 项目源码 | 文件源码
  1. def VshGR(GRlog,itmin,itmax): # Usando o perfil GR
  2.  
  3.  
  4. GRmin = np.nanmin(GRlog)
  5. GRminInt = GRlog[(GRlog<=(GRmin*(1+itmin/100)))] # Valores do GRmin
  6. GRminm = np.mean(GRminInt) # Media dos valores de GRmin
  7.  
  8. GRmax = np.nanmax(GRlog)
  9. GRmaxInt = GRlog[(GRlog>=(GRmax*(1-itmax/100)))] # Valores de GRmax
  10. GRmaxm = np.mean(GRmaxInt) # Media dos valores de GRmax
  11.  
  12. Vsh = 100*(GRlog-GRminm)/(GRmaxm-GRminm) # Volume de argila
  13.  
  14. for i in range(len(Vsh)):
  15. if (Vsh[i] > 100):
  16. Vsh[i] = 100
  17.  
  18. elif (Vsh[i] < 0):
  19. Vsh[i] = 0
  20.  
  21.  
  22. print GRmin, GRminm, GRmax, GRmaxm, np.nanmin(Vsh), np.nanmax(Vsh)
  23.  
  24. return Vsh
项目:gripy    作者:giruenf    | 项目源码 | 文件源码
  1. def VshGR(GRlog, np.nanmax(Vsh)
  2.  
  3. return Vsh
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
  1. def distance_curves(x, ys, q1):
  2. """
  3. distances to the curves.
  4.  
  5. :param x: x values of curves (they have to be sorted).
  6. :param ys: y values of multiple curves sharing x values.
  7. :param q1: a point to measure distance to.
  8. :return:
  9. """
  10.  
  11. # convert curves into a series of startpoints and endpoints
  12. xp = rolling_window(x, 2)
  13. ysp = rolling_window(ys, 2)
  14.  
  15. r = np.nanmin(distance_line_segment(xp[:, 0], ysp[:, :,
  16. xp[:, 1],
  17. q1[0], q1[1]), axis=1)
  18.  
  19. return r
项目:orange3-geo    作者:biolab    | 项目源码 | 文件源码
  1. def set_marker_size(self, attr, update=True):
  2. try:
  3. self._size_attr = variable = self.data.domain[attr]
  4. if len(self.data) == 0:
  5. raise Exception
  6. except Exception:
  7. self._size_attr = None
  8. self._legend_sizes = []
  9. else:
  10. assert variable.is_continuous
  11. self._raw_sizes = values = self.data.get_column_view(variable)[0].astype(float)
  12. # Note,[5,60] is also hardcoded in legend-size-indicator.svg
  13. self._sizes = scale(values, 5, 60).astype(np.uint8)
  14. min = np.nanmin(values)
  15. self._legend_sizes = self._legend_values(variable,
  16. [min, np.nanmax(values)]) if not np.isnan(min) else []
  17. finally:
  18. if update:
  19. self.redraw_markers_overlay_image(new_image=True)
项目:AutoML5    作者:djajetic    | 项目源码 | 文件源码
  1. def sanitize_array(array):
  2. '''''' Replace NaN and Inf (there should not be any!)''''''
  3. a=np.ravel(array)
  4. maxi = np.nanmax((filter(lambda x: x != float(''inf''), a))) # Max except NaN and Inf
  5. mini = np.nanmin((filter(lambda x: x != float(''-inf''), a))) # Mini except NaN and Inf
  6. array[array==float(''inf'')]=maxi
  7. array[array==float(''-inf'')]=mini
  8. mid = (maxi + mini)/2
  9. array[np.isnan(array)]=mid
  10. return array
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def frame_to_series(self, field, frame, columns=None):
  2. """
  3. Convert a frame with a DatetimeIndex and sid columns into a series with
  4. a sid index,using the aggregator defined by the given field.
  5. """
  6. if isinstance(frame, pd.DataFrame):
  7. columns = frame.columns
  8. frame = frame.values
  9.  
  10. if not len(frame):
  11. return pd.Series(
  12. data=(0 if field == ''volume'' else np.nan),
  13. index=columns,
  14. ).values
  15.  
  16. if field in [''price'', ''close'']:
  17. # shortcircuit for full last row
  18. vals = frame[-1]
  19. if np.all(~np.isnan(vals)):
  20. return vals
  21. return ffill(frame)[-1]
  22. elif field == ''open'':
  23. return bfill(frame)[0]
  24. elif field == ''volume'':
  25. return np.nansum(frame, axis=0)
  26. elif field == ''high'':
  27. return np.nanmax(frame, axis=0)
  28. elif field == ''low'':
  29. return np.nanmin(frame, axis=0)
  30. else:
  31. raise ValueError("UnkNown field {}".format(field))
项目:astrobase    作者:waqasbhatti    | 项目源码 | 文件源码
  1. def extract_img_background(img_array,
  2. custom_limits=None,
  3. median_diffbelow=200.0,
  4. image_min=None):
  5. ''''''
  6. This extracts the background of the image array provided:
  7.  
  8. - masks the array to only values between the median and the min of flux
  9. - then returns the median value in 3 x 3 stamps.
  10.  
  11. img_array = image to find the background for
  12.  
  13. custom_limits = use this to provide custom median and min limits for the
  14. background extraction
  15.  
  16. median_diffbelow = subtract this value from the median to get the upper
  17. bound for background extraction
  18.  
  19. image_min = use this value as the lower bound for background extraction
  20.  
  21. ''''''
  22.  
  23. if not custom_limits:
  24.  
  25. backmax = np.median(img_array)-median_diffbelow
  26. backmin = image_min if image_min is not None else np.nanmin(img_array)
  27.  
  28. else:
  29.  
  30. backmin, backmax = custom_limits
  31.  
  32. masked = npma.masked_outside(img_array, backmin, backmax)
  33. backmasked = npma.median(masked)
  34.  
  35. return backmasked
  36.  
  37.  
  38. ## IMAGE SECTION FUNCTIONS ##
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def quickMinMax(self, data):
  2. """
  3. Estimate the min/max values of *data* by subsampling.
  4. """
  5. while data.size > 1e6:
  6. ax = np.argmax(data.shape)
  7. sl = [slice(None)] * data.ndim
  8. sl[ax] = slice(None, 2)
  9. data = data[sl]
  10. return nanmin(data), nanmax(data)
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def dataBounds(self, ax, frac=1.0, orthoRange=None):
  2. if frac >= 1.0 and orthoRange is None and self.bounds[ax] is not None:
  3. return self.bounds[ax]
  4.  
  5. #self.prepareGeometryChange()
  6. if self.data is None or len(self.data) == 0:
  7. return (None, None)
  8.  
  9. if ax == 0:
  10. d = self.data[''x'']
  11. d2 = self.data[''y'']
  12. elif ax == 1:
  13. d = self.data[''y'']
  14. d2 = self.data[''x'']
  15.  
  16. if orthoRange is not None:
  17. mask = (d2 >= orthoRange[0]) * (d2 <= orthoRange[1])
  18. d = d[mask]
  19. d2 = d2[mask]
  20.  
  21. if frac >= 1.0:
  22. self.bounds[ax] = (np.nanmin(d) - self._maxSpotWidth*0.7072, np.nanmax(d) + self._maxSpotWidth*0.7072)
  23. return self.bounds[ax]
  24. elif frac <= 0.0:
  25. raise Exception("Value for parameter ''frac'' must be > 0. (got %s)" % str(frac))
  26. else:
  27. mask = np.isfinite(d)
  28. d = d[mask]
  29. return np.percentile(d, [50 * (1 - frac), 50 * (1 + frac)])
项目:NeoAnalysis    作者:neoanalysis    | 项目源码 | 文件源码
  1. def quickMinMax(self, nanmax(data)
项目:AnomalyDetection    作者:JayZhuCoding    | 项目源码 | 文件源码
  1. def normalize_data(self, values):
  2. normalized_values = copy.deepcopy(values)
  3. data = np.array(values, dtype=float)[:, 0:5]
  4. data_min = np.nanmin(data, 0)
  5. data_max = np.nanmax(data, 0)
  6. print data_min
  7. print data_max
  8. for i in range(len(values)):
  9. for j in range(5):
  10. normalized_values[i][j] = np.abs(values[i][j] - data_min[j]) / np.abs(data_max[j] - data_min[j])
  11. return normalized_values, data_min, data_max
项目:SNPmatch    作者:Gregor-Mendel-Institute    | 项目源码 | 文件源码
  1. def writeBinData(out_file, i, GenotypeData, scoreList, NumInfoSites):
  2. num_lines = len(GenotypeData.accessions)
  3. (likeliscore, likeliHoodratio) = snpmatch.calculate_likelihoods(scoreList, NumInfoSites)
  4. if len(likeliscore) > 0:
  5. NumAmb = np.where(likeliHoodratio < snpmatch.lr_thres)[0]
  6. if len(NumAmb) >= 1 and len(NumAmb) < num_lines:
  7. try:
  8. nextLikeli = np.nanmin(likeliHoodratio[np.where(likeliHoodratio > snpmatch.lr_thres)[0]])
  9. except:
  10. nextLikeli = 1
  11. for k in NumAmb:
  12. score = float(scoreList[k])/NumInfoSites[k]
  13. out_file.write("%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n" % (GenotypeData.accessions[k], int(scoreList[k]), NumInfoSites[k], score, likeliscore[k], nextLikeli, len(NumAmb), i+1))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def image_as_uint8(im):
  2. """ Convert the given image to uint8
  3.  
  4. If the dtype is already uint8,it is returned as-is. If the image
  5. is float,and all values are between 0 and 1,the values are
  6. multiplied by 255. In all other situations,the values are scaled
  7. such that the minimum value becomes 0 and the maximum value becomes
  8. 255.
  9. """
  10. if not isinstance(im, np.ndarray):
  11. raise ValueError(''image must be a numpy array'')
  12. dtype_str = str(im.dtype)
  13. # Already uint8?
  14. if dtype_str == ''uint8'':
  15. return im
  16. # Handle float
  17. mi, ma = np.nanmin(im), np.nanmax(im)
  18. if dtype_str.startswith(''float''):
  19. if mi >= 0 and ma <= 1:
  20. mi, ma = 0, 1
  21. # Now make float copy before we scale
  22. im = im.astype(''float32'')
  23. # Scale the values between 0 and 255
  24. if np.isfinite(mi) and np.isfinite(ma):
  25. if mi:
  26. im -= mi
  27. if ma != 255:
  28. im *= 255.0 / (ma - mi)
  29. assert np.nanmax(im) < 256
  30. return im.astype(np.uint8)
  31.  
  32.  
  33. # currently not used ... the only use it to easly provide the global Meta info
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_masked(self):
  2. mat = np.ma.fix_invalid(_ndat)
  3. msk = mat._mask.copy()
  4. for f in [np.nanmin]:
  5. res = f(mat, axis=1)
  6. tgt = f(_ndat, axis=1)
  7. assert_equal(res, tgt)
  8. assert_equal(mat._mask, msk)
  9. assert_(not np.isinf(mat).any())
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_nanmin(self):
  2. tgt = np.min(self.mat)
  3. for mat in self.integer_arrays():
  4. assert_equal(np.nanmin(mat), tgt)
项目:segyviewer    作者:Statoil    | 项目源码 | 文件源码
  1. def data(self, data):
  2. """ :type: numppy.ndarray """
  3. self._assert_shape(data, self._x_indexes, self._y_indexes)
  4. data[data == -np.inf] = 0.0
  5. data[data == np.inf] = 0.0
  6. self._data = data
  7. self._min_value = np.nanmin(self.data)
  8. self._max_value = np.nanmax(self.data)
  9. self._data_x_indexes = list(range(data.shape[0]))
  10. self._data_y_indexes = list(range(data.shape[1]))
  11. self._dirty = False
项目:AutoML4    作者:djajetic    | 项目源码 | 文件源码
  1. def sanitize_array(array):
  2. '''''' Replace NaN and Inf (there should not be any!)''''''
  3. a=np.ravel(array)
  4. maxi = np.nanmax((filter(lambda x: x != float(''inf''), a))) # Mini except NaN and Inf
  5. array[array==float(''inf'')]=maxi
  6. array[array==float(''-inf'')]=mini
  7. mid = (maxi + mini)/2
  8. array[np.isnan(array)]=mid
  9. return array
项目:automl_gpu    作者:abhishekkrthakur    | 项目源码 | 文件源码
  1. def sanitize_array(array):
  2. '''''' Replace NaN and Inf (there should not be any!)''''''
  3. a=np.ravel(array)
  4. maxi = np.nanmax((filter(lambda x: x != float(''inf''), a))) # Mini except NaN and Inf
  5. array[array==float(''inf'')]=maxi
  6. array[array==float(''-inf'')]=mini
  7. mid = (maxi + mini)/2
  8. array[np.isnan(array)]=mid
  9. return array
项目:HARK    作者:econ-ark    | 项目源码 | 文件源码
  1. def _evaluate(self,x):
  2. ''''''
  3. Returns the level of the function at each value in x as the minimum among
  4. all of the functions. Only called internally by HARKinterpolator1D.__call__.
  5. ''''''
  6. if _isscalar(x):
  7. y = np.nanmin([f(x) for f in self.functions])
  8. else:
  9. m = len(x)
  10. fx = np.zeros((m,self.funcCount))
  11. for j in range(self.funcCount):
  12. fx[:,j] = self.functions[j](x)
  13. y = np.nanmin(fx,axis=1)
  14. return y
项目:HARK    作者:econ-ark    | 项目源码 | 文件源码
  1. def _evaluate(self,x,y):
  2. ''''''
  3. Returns the level of the function at each value in (x,y) as the minimum
  4. among all of the functions. Only called internally by
  5. HARKinterpolator2D.__call__.
  6. ''''''
  7. if _isscalar(x):
  8. f = np.nanmin([f(x,y) for f in self.functions])
  9. else:
  10. m = len(x)
  11. temp = np.zeros((m,self.funcCount))
  12. for j in range(self.funcCount):
  13. temp[:,j] = self.functions[j](x,y)
  14. f = np.nanmin(temp,axis=1)
  15. return f
项目:HARK    作者:econ-ark    | 项目源码 | 文件源码
  1. def _evaluate(self,y,z):
  2. ''''''
  3. Returns the level of the function at each value in (x,y,z) as the minimum
  4. among all of the functions. Only called internally by
  5. HARKinterpolator3D.__call__.
  6. ''''''
  7. if _isscalar(x):
  8. f = np.nanmin([f(x,z) for f in self.functions])
  9. else:
  10. m = len(x)
  11. temp = np.zeros((m,z)
  12. f = np.nanmin(temp,axis=1)
  13. return f
项目:trappist1    作者:rodluger    | 项目源码 | 文件源码
  1. def replot(self, val):
  2. ''''''
  3.  
  4. ''''''
  5.  
  6. # Update plot
  7. self.cadence = int(val)
  8. self.implot.set_data(self.images[int(val)])
  9. self.implot.set_clim(vmin = np.nanmin(self.images[int(val)]), vmax = np.nanmax(self.images[int(val)]))
  10. self.tracker1.set_xdata([self.time[self.cadence], self.time[self.cadence]])
  11. self.tracker2.set_xdata([self.time[self.cadence], self.time[self.cadence]])
  12. self.update_bkg()
  13. self.update_lc()
  14. self.update_lcbkg()
  15. self.fig.canvas.draw()
项目:tadtool    作者:vaquerizaslab    | 项目源码 | 文件源码
  1. def vmin(self):
  2. return self._vmin if self._vmin else np.nanmin(self.hic_matrix)
项目:tadtool    作者:vaquerizaslab    | 项目源码 | 文件源码
  1. def _plot(self, region=None, cax=None):
  2. da_sub, regions_sub = sub_data_regions(self.da, self.regions, region)
  3.  
  4. da_sub_masked = np.ma.MaskedArray(da_sub, mask=np.isnan(da_sub))
  5. bin_coords = np.r_[[(x.start - 1) for x in regions_sub], regions_sub[-1].end]
  6. x, y = np.meshgrid(bin_coords, self.window_sizes)
  7.  
  8. self.mesh = self.ax.pcolormesh(x, da_sub_masked, cmap=self.colormap, vmax=self.vmax)
  9. self.colorbar = plt.colorbar(self.mesh, cax=cax, orientation="vertical")
  10. self.window_size_line = self.ax.axhline(self.current_window_size, color=''red'')
  11.  
  12. if self.log_y:
  13. self.ax.set_yscale("log")
  14. self.ax.set_ylim((np.nanmin(self.window_sizes), np.nanmax(self.window_sizes)))
项目:tadtool    作者:vaquerizaslab    | 项目源码 | 文件源码
  1. def _plot(self, cax=None):
  2. self._new_region(region)
  3. bin_coords = [(x.start - 1) for x in self.sr]
  4. ds = self.da_sub[self.init_row]
  5. self.line, = self.ax.plot(bin_coords, ds)
  6. if not self.is_symmetric:
  7. self.current_cutoff = (self.ax.get_ylim()[1] - self.ax.get_ylim()[0]) / 2 + self.ax.get_ylim()[0]
  8. else:
  9. self.current_cutoff = self.ax.get_ylim()[1]/ 2
  10. self.ax.axhline(0.0, linestyle=''dashed'', color=''grey'')
  11. self.cutoff_line = self.ax.axhline(self.current_cutoff, color=''r'')
  12. if self.is_symmetric:
  13. self.cutoff_line_mirror = self.ax.axhline(-1*self.current_cutoff, color=''r'')
  14. self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds)))
项目:tadtool    作者:vaquerizaslab    | 项目源码 | 文件源码
  1. def update(self, ix=None, cutoff=None, update_canvas=True):
  2. if region is not None:
  3. self._new_region(region)
  4.  
  5. if ix is not None and ix != self.current_ix:
  6. ds = self.da_sub[ix]
  7. self.current_ix = ix
  8. self.line.set_ydata(ds)
  9. self.ax.set_ylim((np.nanmin(ds), np.nanmax(ds)))
  10.  
  11. if cutoff is None:
  12. if not self.is_symmetric:
  13. self.update(cutoff=(self.ax.get_ylim()[1]-self.ax.get_ylim()[0])/2 + self.ax.get_ylim()[0],
  14. update_canvas=False)
  15. else:
  16. self.update(cutoff=self.ax.get_ylim()[1] / 2, update_canvas=False)
  17.  
  18. if update_canvas:
  19. self.fig.canvas.draw()
  20.  
  21. if cutoff is not None and cutoff != self.current_cutoff:
  22. if self.is_symmetric:
  23. self.current_cutoff = abs(cutoff)
  24. else:
  25. self.current_cutoff = cutoff
  26. self.cutoff_line.set_ydata(self.current_cutoff)
  27. if self.is_symmetric:
  28. self.cutoff_line_mirror.set_ydata(-1*self.current_cutoff)
  29.  
  30. if update_canvas:
  31. self.fig.canvas.draw()
项目:smoomapy    作者:mthh    | 项目源码 | 文件源码
  1. def define_levels(self, nb_class, disc_func):
  2. pot = self.pot
  3. _min = np.nanmin(pot)
  4.  
  5. if not nb_class:
  6. nb_class = int(get_opt_nb_class(len(pot)) - 2)
  7. if not disc_func or "prog_geom" in disc_func:
  8. levels = [_min] + [
  9. np.nanmax(pot) / i for i in range(1, nb_class + 1)][::-1]
  10. elif "equal_interval" in disc_func:
  11. _bin = np.nanmax(pot) / nb_class
  12. levels = [_min] + [_bin * i for i in range(1, nb_class+1)]
  13. elif "percentiles" in disc_func:
  14. levels = np.percentile(
  15. np.concatenate((pot[pot.nonzero()], np.array([_min]))),
  16. np.linspace(0.0, 100.0, nb_class+1))
  17. elif "jenks" in disc_func:
  18. levels = list(jenks_breaks(np.concatenate(
  19. ([_min], pot[pot.nonzero()])), nb_class))
  20. levels[0] = levels[0] - _min * 0.01
  21. elif "head_tail" in disc_func:
  22. levels = head_tail_breaks(np.concatenate(
  23. ([_min], pot[pot.nonzero()])))
  24. elif "maximal_breaks" in disc_func:
  25. levels = maximal_breaks(np.concatenate(
  26. ([_min], nb_class)
  27. else:
  28. raise ValueError
  29.  
  30. return levels
项目:orange3-educational    作者:biolab    | 项目源码 | 文件源码
  1. def set_range(self, x_data, y_data):
  2. min_x, max_x = np.nanmin(x_data), np.nanmax(x_data)
  3. min_y, max_y = np.nanmin(y_data), np.nanmax(y_data)
  4. self.plotview.setRange(
  5. QRectF(min_x, min_y, max_x - min_x, max_y - min_y),
  6. padding=0.025)
  7. self.plotview.replot()

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy.random.random & numpy.ndarray.astype & numpy.arange

numpy.random.random & numpy.ndarray.astype & numpy.arange

今天看到这样一句代码:

xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值

要理解这两句代码需要理解三个函数

1、生成随机数

numpy.random.random(size=None) 

size为None时,返回float。

size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组

 

2、对numpy数组中每一个元素进行类型转换

numpy.ndarray.astype(dtype)

返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]

 

3、获取等差数列

numpy.arange([start,]stop,[step,]dtype=None)

功能类似python中自带的range()和numpy中的numpy.linspace

返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel(a, order=''C'')

  Return a flattened array

numpy.chararray.flatten(order=''C'')

  Return a copy of the array collapsed into one dimension

numpy.squeeze(a, axis=None)

  Remove single-dimensional entries from the shape of an array.

 

相同点: 将多维数组 降为 一维数组

不同点:

  ravel() 返回的是视图(view),意味着改变元素的值会影响原始数组元素的值;

  flatten() 返回的是拷贝,意味着改变元素的值不会影响原始数组;

  squeeze()返回的是视图(view),仅仅是将shape中dimension为1的维度去掉;

 

ravel()示例:

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.ravel()
16 print("a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 
20 print(a)
21 log_type(''a'',a)

 

flatten()示例

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.flatten()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

squeeze()示例:

1. 没有single-dimensional entries的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

从结果中可以看到,当没有single-dimensional entries时,squeeze()返回额数组对象是一个view,而不是copy。

 

2. 有single-dimentional entries 的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10 
11 a = np.floor(10*np.random.random((1,3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

一、Numpy数组创建

 part 1:np.linspace(起始值,终止值,元素总个数

 

import numpy as np
''''''
numpy中的ndarray数组
''''''

ary = np.array([1, 2, 3, 4, 5])
print(ary)
ary = ary * 10
print(ary)

''''''
ndarray对象的创建
''''''
# 创建二维数组
# np.array([[],[],...])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)

# np.arange(起始值, 结束值, 步长(默认1))
b = np.arange(1, 10, 1)
print(b)

print("-------------np.zeros(数组元素个数, dtype=''数组元素类型'')-----")
# 创建一维数组:
c = np.zeros(10)
print(c, ''; c.dtype:'', c.dtype)

# 创建二维数组:
print(np.zeros ((3,4)))

print("----------np.ones(数组元素个数, dtype=''数组元素类型'')--------")
# 创建一维数组:
d = np.ones(10, dtype=''int64'')
print(d, ''; d.dtype:'', d.dtype)

# 创建三维数组:
print(np.ones( (2,3,4), dtype=np.int32 ))
# 打印维度
print(np.ones( (2,3,4), dtype=np.int32 ).ndim)  # 返回:3(维)

 

结果图:

 

part 2 :np.linspace ( 起始值,终止值,元素总个数)

 

import numpy as np
a = np.arange( 10, 30, 5 )

b = np.arange( 0, 2, 0.3 )

c = np.arange(12).reshape(4,3)

d = np.random.random((2,3))  # 取-1到1之间的随机数,要求设置为诶2行3列的结构

print(a)
print(b)
print(c)
print(d)

print("-----------------")
from numpy import pi
print(np.linspace( 0, 2*pi, 100 ))

print("-------------np.linspace(起始值,终止值,元素总个数)------------------")
print(np.sin(np.linspace( 0, 2*pi, 100 )))

 

结果图:

 

 

 

 

二、Numpy的ndarray对象属性:

数组的结构:array.shape

数组的维度:array.ndim

元素的类型:array.dtype

数组元素的个数:array.size

数组的索引(下标):array[0]

 

''''''
数组的基本属性
''''''
import numpy as np

print("--------------------案例1:------------------------------")
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)     # 打印数组结构
print(len(a))      # 打印有多少行
print(a.ndim)     # 打印维度
print(a.dtype)    # 打印a数组内的元素的数据类型
# print(a.dtype.name)
print(a.size)    # 打印数组的总元素个数


print("-------------------案例2:---------------------------")
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)

# 测试数组的基本属性
print(''a.shape:'', a.shape)
print(''a.size:'', a.size)
print(''len(a):'', len(a))
# a.shape = (6, )  # 此格式可将原数组结构变成1行6列的数据结构
# print(a, ''a.shape:'', a.shape)

# 数组元素的索引
ary = np.arange(1, 28)
ary.shape = (3, 3, 3)   # 创建三维数组
print("ary.shape:",ary.shape,"\n",ary )

print("-----------------")
print(''ary[0]:'', ary[0])
print(''ary[0][0]:'', ary[0][0])
print(''ary[0][0][0]:'', ary[0][0][0])
print(''ary[0,0,0]:'', ary[0, 0, 0])

print("-----------------")


# 遍历三维数组:遍历出数组里的每个元素
for i in range(ary.shape[0]):
    for j in range(ary.shape[1]):
        for k in range(ary.shape[2]):
            print(ary[i, j, k], end='' '')
            

 

结果图:

 

今天关于Python numpy 模块-nanmin() 实例源码python中numpy模块的介绍到此结束,谢谢您的阅读,有关Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性等更多相关知识的信息可以在本站进行查询。

本文标签: