GVKun编程网logo

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

5

本文将分享Pythonnumpy模块-nanargmin()实例源码的详细内容,并且还将对python中numpy模块进行详尽解释,此外,我们还将为大家带来关于Jupyter中的Numpy在打印时出错

本文将分享Python numpy 模块-nanargmin() 实例源码的详细内容,并且还将对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 模块-nanargmin() 实例源码(python中numpy模块)

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

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

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

项目:trappist1    作者:rodluger    | 项目源码 | 文件源码
  1. def mouse_drag(self, event):
  2. ''''''
  3.  
  4. ''''''
  5.  
  6. if event.inaxes == self.ax and event.button == 1:
  7.  
  8. # Index of nearest point
  9. i = np.nanargmin(((event.xdata - self.x) / self.nx) ** 2)
  10. j = np.nanargmin(((event.ydata - self.y) / self.ny) ** 2)
  11.  
  12. if (i == self.last_i) and (j == self.last_j):
  13. return
  14. else:
  15. self.last_i = i
  16. self.last_j = j
  17.  
  18. # Toggle pixel
  19. if self.aperture[j,i]:
  20. self.aperture[j,i] = 0
  21. else:
  22. self.aperture[j,i] = 1
  23.  
  24. # Update the contour
  25. self.update()
项目:trappist1    作者:rodluger    | 项目源码 | 文件源码
  1. def mouse_click(self, event):
  2. ''''''
  3.  
  4. ''''''
  5.  
  6. if event.mouseevent.inaxes == self.ax:
  7.  
  8. # Index of nearest point
  9. i = np.nanargmin(((event.mouseevent.xdata - self.x) / self.nx) ** 2)
  10. j = np.nanargmin(((event.mouseevent.ydata - self.y) / self.ny) ** 2)
  11. self.last_i = i
  12. self.last_j = j
  13.  
  14. # Toggle pixel
  15. if self.aperture[j,i] = 1
  16.  
  17. # Update the contour
  18. self.update()
项目:pycma    作者:CMA-ES    | 项目源码 | 文件源码
  1. def update(self, arx, xarchive=None, arf=None, evals=None):
  2. """checks for better solutions in list ``arx``.
  3.  
  4. Based on the smallest corresponding value in ``arf``,
  5. alternatively,`update` may be called with a `BestSolution`
  6. instance like ``update(another_best_solution)`` in which case
  7. the better solution becomes the current best.
  8.  
  9. ``xarchive`` is used to retrieve the genotype of a solution.
  10. """
  11. if isinstance(arx, BestSolution):
  12. if self.evalsall is None:
  13. self.evalsall = arx.evalsall
  14. elif arx.evalsall is not None:
  15. self.evalsall = max((self.evalsall, arx.evalsall))
  16. if arx.f is not None and arx.f < np.inf:
  17. self.update([arx.x], xarchive, [arx.f], arx.evals)
  18. return self
  19. assert arf is not None
  20. # find failsave minimum
  21. try:
  22. minidx = np.nanargmin(arf)
  23. except ValueError:
  24. return
  25. if minidx is np.nan:
  26. return
  27. minarf = arf[minidx]
  28. # minarf = reduce(lambda x,y: y if y and y is not np.nan
  29. # and y < x else x,arf,np.inf)
  30. if minarf < np.inf and (minarf < self.f or self.f is None):
  31. self.x, self.f = arx[minidx], arf[minidx]
  32. if xarchive is not None and xarchive.get(self.x) is not None:
  33. self.x_geno = xarchive[self.x].get(''geno'')
  34. else:
  35. self.x_geno = None
  36. self.evals = None if not evals else evals - len(arf) + minidx + 1
  37. self.evalsall = evals
  38. elif evals:
  39. self.evalsall = evals
  40. self.last.x = arx[minidx]
  41. self.last.f = minarf
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_nanargmin(self):
  2. tgt = np.argmin(self.mat)
  3. for mat in self.integer_arrays():
  4. assert_equal(np.nanargmin(mat), tgt)
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
  1. def update(self, evals=None):
  2. """checks for better solutions in list `arx`.
  3.  
  4. Based on the smallest corresponding value in `arf`,`update` may be called with a `BestSolution`
  5. instance like ``update(another_best_solution)`` in which case
  6. the better solution becomes the current best.
  7.  
  8. `xarchive` is used to retrieve the genotype of a solution.
  9.  
  10. """
  11. if isinstance(arx, arx.evals)
  12. return self
  13. assert arf is not None
  14. # find failsave minimum
  15. minidx = np.nanargmin(arf)
  16. if minidx is np.nan:
  17. return
  18. minarf = arf[minidx]
  19. # minarf = reduce(lambda x, arf[minidx]
  20. if xarchive is not None and xarchive.get(self.x) is not None:
  21. self.x_geno = xarchive[self.x].get(''geno'')
  22. else:
  23. self.x_geno = None
  24. self.evals = None if not evals else evals - len(arf) + minidx + 1
  25. self.evalsall = evals
  26. elif evals:
  27. self.evalsall = evals
  28. self.last.x = arx[minidx]
  29. self.last.f = minarf
项目:rllabplusplus    作者:shaneshixiang    | 项目源码 | 文件源码
  1. def update(self, arf[minidx]
  2. if xarchive is not None and xarchive.get(self.x) is not None:
  3. self.x_geno = xarchive[self.x].get(''geno'')
  4. else:
  5. self.x_geno = None
  6. self.evals = None if not evals else evals - len(arf) + minidx + 1
  7. self.evalsall = evals
  8. elif evals:
  9. self.evalsall = evals
  10. self.last.x = arx[minidx]
  11. self.last.f = minarf
项目:cma    作者:hardmaru    | 项目源码 | 文件源码
  1. def update(self, arf[minidx]
  2. if xarchive is not None and xarchive.get(self.x) is not None:
  3. self.x_geno = xarchive[self.x].get(''geno'')
  4. else:
  5. self.x_geno = None
  6. self.evals = None if not evals else evals - len(arf) + minidx + 1
  7. self.evalsall = evals
  8. elif evals:
  9. self.evalsall = evals
  10. self.last.x = arx[minidx]
  11. self.last.f = minarf
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_nanargmin(self):
  2. tgt = np.argmin(self.mat)
  3. for mat in self.integer_arrays():
  4. assert_equal(np.nanargmin(mat), tgt)
项目:smhr    作者:andycasey    | 项目源码 | 文件源码
  1. def figure_mouse_pick(self, event):
  2. """
  3. Trigger for when the mouse is used to select an item in the figure.
  4.  
  5. :param event:
  6. The matplotlib event.
  7. """
  8.  
  9. ycol = "abundance"
  10. xcol = {
  11. self.ax_excitation_twin: "expot",
  12. self.ax_line_strength_twin: "reduced_equivalent_width"
  13. }[event.inaxes]
  14.  
  15. xscale = np.ptp(event.inaxes.get_xlim())
  16. yscale = np.ptp(event.inaxes.get_ylim())
  17. try:
  18. distance = np.sqrt(
  19. ((self._state_transitions[ycol] - event.ydata)/yscale)**2 \\
  20. + ((self._state_transitions[xcol] - event.xdata)/xscale)**2)
  21. except AttributeError:
  22. # Stellar parameters have not been measured yet
  23. return None
  24.  
  25. index = np.nanargmin(distance)
  26.  
  27. # Because the state transitions are linked to the parent source model of
  28. # the table view,we will have to get the proxy index.
  29. proxy_index = self.table_view.model().mapFromSource(
  30. self.proxy_spectral_models.sourceModel().createIndex(index, 0)).row()
  31.  
  32. self.table_view.selectRow(proxy_index)
  33. return None
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def find_min(x, bin_width = 10):
  2. xm = binned_average(x, bin_width=bin_width);
  3. imin = np.nanargmin(xm);
  4. return int((imin + 0.5) * bin_width);
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def find_min(x, bin_width=bin_width);
  2. imin = np.nanargmin(xm);
  3. return int((imin + 0.5) * bin_width);
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def find_min(x, bin_width=bin_width);
  2. imin = np.nanargmin(xm);
  3. return int((imin + 0.5) * bin_width);
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def find_min(x, bin_width=bin_width);
  2. imin = np.nanargmin(xm);
  3. return int((imin + 0.5) * bin_width);
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def find_min(x, bin_width=bin_width);
  2. imin = np.nanargmin(xm);
  3. return int((imin + 0.5) * bin_width);
项目:scikit-gstat    作者:mmaelicke    | 项目源码 | 文件源码
  1. def Variogram(self):
  2. """
  3.  
  4. :return:
  5. """
  6. self.run()
  7.  
  8. # find the best Variogram
  9. idx = np.nanargmin(self.e)
  10.  
  11. return self.V[idx]
项目:motion-classification    作者:matthiasplappert    | 项目源码 | 文件源码
  1. def _select_best_measure_index(curr_measures, args):
  2. idx = None
  3. try:
  4. if args.measure == ''aicc'':
  5. # The best score for AICc is the minimum.
  6. idx = np.nanargmin(curr_measures)
  7. elif args.measure in [''hmm-distance'', ''wasserstein'', ''mahalanobis'']:
  8. # The best score for the l-d measure is the maximum.
  9. idx = np.nanargmax(curr_measures)
  10. except:
  11. idx = random.choice(range(len(curr_measures)))
  12. assert idx is not None
  13. return idx
项目:DeepRepICCV2015    作者:tomrunia    | 项目源码 | 文件源码
  1. def initial_count(classify, test_set_x, data, valid):
  2.  
  3. (valid_st2,valid_st5,valid_st8) = valid
  4. (ns_test_set_x_st2,ns_test_set_x_st5,ns_test_set_x_st8) = data
  5.  
  6. # classify st_2 it is always valid
  7. (st2_count, st2_res, st2_entropy) = count_in_interval(classify, ns_test_set_x_st2, 0, 81) #100 - 19 etc.
  8.  
  9. # check if st5 is valid. if not return st2 count
  10. if (valid_st5 == 1):
  11. (st5_count, st5_res, st5_entropy) = count_in_interval(classify, ns_test_set_x_st5, 21)
  12. else:
  13. st8_entropy = numpy.inf
  14.  
  15. if (valid_st8 == 1):
  16. (st8_count, st8_res, st8_entropy) = count_in_interval(classify, ns_test_set_x_st8, 6)
  17. else:
  18. st8_entropy = numpy.inf
  19.  
  20.  
  21. winner = numpy.nanargmin(numpy.array([st2_entropy, st5_entropy, st8_entropy]))
  22.  
  23. if (winner == 0):
  24. # winner is stride 2
  25. return (st2_count, (st2_res*2/2,st2_res*2/5, st2_res*2/8))
  26. if (winner == 1):
  27. # winner is stride 5
  28. return (st5_count, (st5_res*5/2,st5_res*5/5, st5_res*5/8))
  29. if (winner == 2):
  30. # winner is stride 8
  31. return (st8_count, (st8_res*8/2,st8_res*8/5, st8_res*8/8))
项目:DeepRepICCV2015    作者:tomrunia    | 项目源码 | 文件源码
  1. def get_next_count(classify, valid, global_count, curr_residue, start_frame):
  2.  
  3. (valid_st2,ns_test_set_x_st8) = data
  4. (curr_residue_st2, curr_residue_st5, curr_residue_st8) = curr_residue
  5.  
  6. # classify st_2 it is always valid
  7. (st2_count, curr_residue_st2, (start_frame/2-19), (start_frame/2-19)+20)
  8. # check if st5 is valid. if not return st2 count
  9. if (valid_st5 == 1):
  10. (st5_count, (start_frame/5-19), (start_frame/5-19)+8)
  11. else:
  12. st5_entropy = numpy.inf
  13.  
  14. if (valid_st8 == 1):
  15. (st8_count, curr_residue_st8, (start_frame/8-19), (start_frame/8-19)+5)
  16. else:
  17. st8_entropy = numpy.inf
  18.  
  19. winner = numpy.nanargmin(numpy.array([st2_entropy, st8_entropy]))
  20.  
  21. if (winner == 0):
  22. # winner is stride 2
  23. return (global_count + st2_count, st2_res*2/8))
  24. if (winner == 1):
  25. # winner is stride 5
  26. return (global_count + st5_count, st5_res*5/8))
  27. if (winner == 2):
  28. # winner is stride 8
  29. return (global_count + st8_count, st8_res*8/8))
项目:DeepRepICCV2015    作者:tomrunia    | 项目源码 | 文件源码
  1. def get_remain_count(classify, ns_test_set_x_st2.shape[0])
  2. # check if st5 is valid. if not return st2 count
  3. if (valid_st5 == 1):
  4. (st5_count, ns_test_set_x_st5.shape[0])
  5. else:
  6. st5_entropy = numpy.inf
  7.  
  8. if (valid_st8 == 1):
  9. (st8_count, ns_test_set_x_st8.shape[0])
  10. else:
  11. st8_entropy = numpy.inf
  12.  
  13.  
  14. winner = numpy.nanargmin(numpy.array([st2_entropy, st8_entropy]))
  15.  
  16. if (winner == 0):
  17. # winner is stride 2
  18. return (global_count + st2_count)
  19. if (winner == 1):
  20. # winner is stride 5
  21. return (global_count + st5_count)
  22. if (winner == 2):
  23. # winner is stride 8
  24. return (global_count + st8_count)
项目:DeepRepICCV2015    作者:tomrunia    | 项目源码 | 文件源码
  1. def count_entire_movie(classify, ns_test_set_x_st8.shape[0])
  2. else:
  3. st8_entropy = numpy.inf
  4.  
  5. winner = numpy.nanargmin(numpy.array([st2_entropy, st8_entropy]))
  6.  
  7. if (winner == 0):
  8. # winner is stride 2
  9. return (global_count + st2_count)
  10. if (winner == 1):
  11. # winner is stride 5
  12. return (global_count + st5_count)
  13. if (winner == 2):
  14. # winner is stride 8
  15. return (global_count + st8_count)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_nanargmin(self):
  2. tgt = np.argmin(self.mat)
  3. for mat in self.integer_arrays():
  4. assert_equal(np.nanargmin(mat), tgt)
项目:soinn    作者:fukatani    | 项目源码 | 文件源码
  1. def __find_nearest_nodes(self, num, signal, mahar=True):
  2. #if mahar: return self.__find_nearest_nodes_by_mahar(num,signal)
  3. n = self.nodes.shape[0]
  4. indexes = [0.0] * num
  5. sq_dists = [0.0] * num
  6. D = util.calc_distance(self.nodes, np.asarray([signal] * n))
  7. for i in range(num):
  8. indexes[i] = np.nanargmin(D)
  9. sq_dists[i] = D[indexes[i]]
  10. D[indexes[i]] = float(''nan'')
  11. return indexes, sq_dists
项目:gail-driver    作者:sisl    | 项目源码 | 文件源码
  1. def update(self, arf[minidx]
  2. if xarchive is not None and xarchive.get(self.x) is not None:
  3. self.x_geno = xarchive[self.x].get(''geno'')
  4. else:
  5. self.x_geno = None
  6. self.evals = None if not evals else evals - len(arf) + minidx + 1
  7. self.evalsall = evals
  8. elif evals:
  9. self.evalsall = evals
  10. self.last.x = arx[minidx]
  11. self.last.f = minarf
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_nanargmin(self):
  2. tgt = np.argmin(self.mat)
  3. for mat in self.integer_arrays():
  4. assert_equal(np.nanargmin(mat), tgt)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_nanargmin(self):
  2. tgt = np.argmin(self.mat)
  3. for mat in self.integer_arrays():
  4. assert_equal(np.nanargmin(mat), tgt)
项目:pactools    作者:pactools    | 项目源码 | 文件源码
  1. def plot(self, ax=None, write_tau=True):
  2. """
  3. Returns
  4. -------
  5. fig : matplotlib.figure.figure
  6. figure instance containing the plot.
  7. """
  8. check_is_fitted(self, ''neg_log_likelihood_'')
  9. if ax is None:
  10. fig = plt.figure()
  11. ax = fig.gca()
  12. else:
  13. fig = ax.figure
  14.  
  15. blue, green, red, purple, yellow, cyan = SEABORN_PALETTES[''deep'']
  16.  
  17. i_best = np.nanargmin(self.neg_log_likelihood_)
  18. ax.plot(self.delays_ms_, self.neg_log_likelihood_, color=purple)
  19. ax.plot(self.delays_ms_[i_best], self.neg_log_likelihood_[i_best], ''D'',
  20. color=red)
  21. ax.set_xlabel(''Delay (ms)'')
  22. ax.set_ylabel(''Neg. log likelihood / T'')
  23. ax.grid(''on'')
  24.  
  25. if write_tau:
  26. ax.text(0.5, 0.80, r''$\\mathrm{Estimated}$'',
  27. horizontalalignment=''center'', transform=ax.transAxes)
  28. ax.text(0.5, 0.66, r''$\\tau_0 = %.0f \\;\\mathrm{ms}$'' %
  29. (self.delays_ms_[i_best], ), horizontalalignment=''center'',
  30. transform=ax.transAxes)
  31.  
  32. return fig
项目:pactools    作者:pactools    | 项目源码 | 文件源码
  1. def test_delay_shape():
  2. est = fast_delay()
  3. assert_equal(est.neg_log_likelihood_.shape, est.delays_ms_.shape)
  4. assert_greater(est.neg_log_likelihood_.shape[0], 1)
  5. i_best = np.nanargmin(est.neg_log_likelihood_)
  6. assert_equal(est.best_delay_ms_, est.delays_ms_[i_best])
项目:rllab    作者:rll    | 项目源码 | 文件源码
  1. def update(self, arf[minidx]
  2. if xarchive is not None and xarchive.get(self.x) is not None:
  3. self.x_geno = xarchive[self.x].get(''geno'')
  4. else:
  5. self.x_geno = None
  6. self.evals = None if not evals else evals - len(arf) + minidx + 1
  7. self.evalsall = evals
  8. elif evals:
  9. self.evalsall = evals
  10. self.last.x = arx[minidx]
  11. self.last.f = minarf
项目:single-cell-classification    作者:whuTommy    | 项目源码 | 文件源码
  1. def optimize_threshold_with_f1(f1c, thresholds, criterion=''max''):
  2. #f1c[np.isnan(f1c)] = 0
  3. if criterion == ''max'':
  4. ti = np.nanargmax(f1c)
  5. else:
  6. ti = np.nanargmin(np.abs(thresholds-0.5*f1c))
  7. #assert(np.all(thresholds>=0))
  8. #idx = (thresholds>=f1c*0.5-mp) & (thresholds<=f1c*0.5+mp)
  9. #assert(np.any(idx))
  10. #ti = np.where(idx)[0][f1c[idx].argmax()]
  11. return thresholds[ti], ti
项目:mplcursors    作者:anntzer    | 项目源码 | 文件源码
  1. def _(artist, event):
  2. offsets = artist.get_offsets()
  3. ds = np.hypot(
  4. *(artist.axes.transData.transform(offsets) - [event.x, event.y]).T)
  5. argmin = np.nanargmin(ds)
  6. if ds[argmin] < artist.get_pickradius():
  7. target = with_attrs(offsets[argmin], index=argmin)
  8. return Selection(artist, target, ds[argmin], None, None)
  9. else:
  10. return None
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
  1. def compute_integral(self, x_s, y_s):
  2. if len(x_s) == 0:
  3. return np.zeros((y_s.shape[0],)) * np.nan
  4. closer = np.nanargmin(abs(x_s - self.limits[0]))
  5. return y_s[:, closer]
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
  1. def compute_draw_info(self, x, ys):
  2. bs = self.compute_baseline(x, ys)
  3. im = np.array([np.nanargmin(abs(x - self.limits[0]))])
  4. dx = [self.limits[0], self.limits[0]]
  5. dys = np.hstack((bs[:, im], ys[:, im]))
  6. return [("curve", (dx, dys, INTEGRATE_DRAW_EDGE_PENARGS)), # line to value
  7. ("dot", (x[im], im]))]
项目:maml_rl    作者:cbfinn    | 项目源码 | 文件源码
  1. def update(self, arf[minidx]
  2. if xarchive is not None and xarchive.get(self.x) is not None:
  3. self.x_geno = xarchive[self.x].get(''geno'')
  4. else:
  5. self.x_geno = None
  6. self.evals = None if not evals else evals - len(arf) + minidx + 1
  7. self.evalsall = evals
  8. elif evals:
  9. self.evalsall = evals
  10. self.last.x = arx[minidx]
  11. self.last.f = minarf
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_nanargmin(self):
  2. tgt = np.argmin(self.mat)
  3. for mat in self.integer_arrays():
  4. assert_equal(np.nanargmin(mat), tgt)
项目:hdmedians    作者:Daleroberts    | 项目源码 | 文件源码
  1. def nanmedoid(a, axis=1, indexonly=False):
  2. """
  3. Compute the medoid along the specified axis,omitting
  4. observations containing NaNs.
  5.  
  6. Returns the medoid of the array elements.
  7.  
  8. Parameters
  9. ----------
  10. a : array_like
  11. Input array or object that can be converted to an array.
  12. axis : int
  13. Axis along which the medoid is computed. The default
  14. is to compute the median along the last axis of the array.
  15. indexonly : bool,optional
  16. If this is set to True,only the index of the medoid is returned.
  17. Returns
  18. -------
  19. medoid : ndarray or int
  20. """
  21. if axis == 1:
  22. diff = a.T[:, :] - a.T
  23. ssum = np.einsum(''ijk,ijk->ij'', diff, diff)
  24. dist = np.nansum(np.sqrt(ssum), axis=1)
  25. mask = np.isnan(a).any(axis=0)
  26. dist[mask] = np.nan
  27. idx = np.nanargmin(dist)
  28. if indexonly:
  29. return idx
  30. else:
  31. return a[:, idx]
  32.  
  33. if axis == 0:
  34. diff = a[:, :] - a
  35. ssum = np.einsum(''ijk, axis=1)
  36. mask = np.isnan(a).any(axis=1)
  37. dist[mask] = np.nan
  38. idx = np.nanargmin(dist)
  39. if indexonly:
  40. return idx
  41. else:
  42. return a[idx, :]
  43.  
  44. raise IndexError("axis {} out of bounds".format(axis))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def nanargmin(a, axis=None):
  2. """
  3. Return the indices of the minimum values in the specified axis ignoring
  4. NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
  5. cannot be trusted if a slice contains only NaNs and Infs.
  6.  
  7. Parameters
  8. ----------
  9. a : array_like
  10. Input data.
  11. axis : int,optional
  12. Axis along which to operate. By default flattened input is used.
  13.  
  14. Returns
  15. -------
  16. index_array : ndarray
  17. An array of indices or a single index value.
  18.  
  19. See Also
  20. --------
  21. argmin,nanargmax
  22.  
  23. Examples
  24. --------
  25. >>> a = np.array([[np.nan,4],[2,3]])
  26. >>> np.argmin(a)
  27. 0
  28. >>> np.nanargmin(a)
  29. 2
  30. >>> np.nanargmin(a,axis=0)
  31. array([1,1])
  32. >>> np.nanargmin(a,axis=1)
  33. array([1,0])
  34.  
  35. """
  36. a, mask = _replace_nan(a, np.inf)
  37. res = np.argmin(a, axis=axis)
  38. if mask is not None:
  39. mask = np.all(mask, axis=axis)
  40. if np.any(mask):
  41. raise ValueError("All-NaN slice encountered")
  42. return res
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def nanargmax(a, axis=None):
  2. """
  3. Return the indices of the maximum values in the specified axis ignoring
  4. NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
  5. results cannot be trusted if a slice contains only NaNs and -Infs.
  6.  
  7.  
  8. Parameters
  9. ----------
  10. a : array_like
  11. Input data.
  12. axis : int,optional
  13. Axis along which to operate. By default flattened input is used.
  14.  
  15. Returns
  16. -------
  17. index_array : ndarray
  18. An array of indices or a single index value.
  19.  
  20. See Also
  21. --------
  22. argmax,nanargmin
  23.  
  24. Examples
  25. --------
  26. >>> a = np.array([[np.nan,3]])
  27. >>> np.argmax(a)
  28. 0
  29. >>> np.nanargmax(a)
  30. 1
  31. >>> np.nanargmax(a,0])
  32. >>> np.nanargmax(a,1])
  33.  
  34. """
  35. a, -np.inf)
  36. res = np.argmax(a, axis=axis)
  37. if np.any(mask):
  38. raise ValueError("All-NaN slice encountered")
  39. return res
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def nanargmin(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def nanargmax(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:py-NnK    作者:FMassin    | 项目源码 | 文件源码
  1. def nicecolorbar(self,
  2. axcb=None,
  3. reflevel=None,
  4. label=None,
  5. vmax=None,
  6. vmin=None,
  7. data=None,
  8. loc=''head right'',
  9. fontsize=8,
  10. ticks = None):
  11. if not axcb:
  12. axcb = matplotlib.pyplot.gca()
  13. divider = make_axes_locatable(axcb)
  14. # this code is from
  15. # http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axes-grid1
  16. cax = divider.append_axes("right", size="2%", pad=0.15)
  17.  
  18.  
  19.  
  20. levels = numpy.asarray([0.001,0.0025,0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,25,50,100,250,500,1000])
  21. if vmax!= None and vmin != None:
  22. level = levels[numpy.nanargmin(abs((vmax - vmin)/5 - levels))]
  23. ticks = numpy.arange(vmin, vmax, level)
  24.  
  25. elif vmax :
  26. level = levels[numpy.nanargmin(abs((vmax - numpy.nanmin(data))/5 - levels))]
  27. ticks = numpy.arange(numpy.nanmin(data), level)
  28. elif data is not None:
  29. level = None #levels[numpy.nanargmin(abs((numpy.nanmax(data) - numpy.nanmin(data))/5 - levels))]
  30. ticks = None #numpy.arange(numpy.nanmin(data),numpy.nanmax(data),level)
  31. #ticks -= numpy.nanmin(abs(ticks))
  32.  
  33. cb = matplotlib.pyplot.colorbar(self,
  34. cax=cax,
  35. label=label,
  36. orientation=''vertical'',
  37. extend=''both'',
  38. spacing=''uniform'',
  39. ticks=ticks)
  40. if vmax!= None and vmin != None:
  41. #print(ticks,vmin,vmax)
  42. cb.set_clim(vmin, vmax)
  43.  
  44. cb.ax.yaxis.set_ticks_position(''right'')
  45. cb.ax.yaxis.set_label_position(''right'')
  46. cb.ax.set_yticklabels(cb.ax.get_yticklabels(), rotation=''vertical'',fontsize=fontsize)
  47.  
  48. #if reflevel:
  49. # cb.ax.axhline((reflevel-min(cb.get_clim()))/numpy.diff(cb.get_clim()),zorder=999,color=''k'',linewidth=2)
  50. return cb
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def nanargmin(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def nanargmax(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def nanargmin(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def nanargmax(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def nanargmin(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def nanargmax(a, axis=axis)
  2. if np.any(mask):
  3. raise ValueError("All-NaN slice encountered")
  4. return res
项目:calcam    作者:euratom-software    | 项目源码 | 文件源码
  1. def get_ray_lengths(self,x=None,y=None,PositionTol = 3,Coords=''display''):
  2.  
  3. # Work out ray lengths for all raytraced pixels
  4. RayLength = np.sqrt(np.sum( (self.ray_end_coords - self.ray_start_coords) **2,axis=-1))
  5. # If no x and y given,return them all
  6. if x is None and y is None:
  7. if self.fullchip:
  8. if Coords.lower() == ''display'':
  9. return RayLength
  10. else:
  11. return self.transform.display_to_original_image(RayLength,binning=self.binning)
  12. else:
  13. return RayLength
  14. else:
  15. if self.x is None or self.y is None:
  16. raise Exception(''This ray data does not have x and y pixel indices!'')
  17.  
  18. # Otherwise,return the ones at given x and y pixel coords.
  19. if np.shape(x) != np.shape(y):
  20. raise ValueError(''x and y arrays must be the same shape!'')
  21. else:
  22.  
  23. if Coords.lower() == ''original'':
  24. x,y = self.transform.original_to_display_coords(x,y)
  25.  
  26. orig_shape = np.shape(x)
  27. x = np.reshape(x,np.size(x),order=''F'')
  28. y = np.reshape(y,np.size(y),order=''F'')
  29. RL = np.zeros(np.shape(x))
  30. RayLength = RayLength.flatten()
  31. xflat = self.x.flatten()
  32. yflat = self.y.flatten()
  33. for pointno in range(x.size):
  34. if np.isnan(x[pointno]) or np.isnan(y[pointno]):
  35. RL[pointno] = np.nan
  36. continue
  37.  
  38. deltaX = xflat - x[pointno]
  39. deltaY = yflat - y[pointno]
  40. deltaR = np.sqrt(deltaX**2 + deltaY**2)
  41. if np.nanmin(deltaR) <= PositionTol:
  42. RL[pointno] = RayLength[np.nanargmin(deltaR)]
  43. else:
  44. raise Exception(''No ray-traced pixel within PositionTol of requested pixel!'')
  45. return np.reshape(RL,orig_shape,order=''F'')
  46.  
  47.  
  48. # Return unit vectors of sight-line direction for each pixel.
项目:mplcursors    作者:anntzer    | 项目源码 | 文件源码
  1. def _compute_projection_pick(artist, path, xy):
  2. """Project *xy* on *path* to obtain a `Selection` for *artist*.
  3.  
  4. *path* is first transformed to screen coordinates using the artist
  5. transform,and the target of the returned `Selection` is transformed
  6. back to data coordinates using the artist *axes* inverse transform. The
  7. `Selection` `index` is returned as a float. This function returns ``None``
  8. for degenerate inputs.
  9.  
  10. The caller is responsible for converting the index to the proper class if
  11. needed.
  12. """
  13. transform = artist.get_transform().frozen()
  14. tpath = (path.cleaned(transform) if transform.is_affine
  15. # `cleaned` only handles affine transforms.
  16. else transform.transform_path(path).cleaned())
  17. # `cleaned` should return a path where the first element is `MOVeto`,the
  18. # following are `LINeto` or `CLOSEpoly`,and the last one is `STOP`,i.e.
  19. # codes = path.codes
  20. # assert (codes[0],codes[-1]) == (path.MOVeto,path.STOP)
  21. # assert np.in1d(codes[1:-1],[path.LINeto,path.CLOSEpoly]).all()
  22. vertices = tpath.vertices[:-1]
  23. codes = tpath.codes[:-1]
  24. vertices[codes == tpath.CLOSEpoly] = vertices[0]
  25. # Unit vectors for each segment.
  26. us = vertices[1:] - vertices[:-1]
  27. ls = np.hypot(*us.T)
  28. with np.errstate(invalid="ignore"):
  29. # Results in 0/0 for repeated consecutive points.
  30. us /= ls[:, None]
  31. # Vectors from each vertex to the event (overwritten below).
  32. vs = xy - vertices[:-1]
  33. # Clipped dot products -- `einsum` cannot be done in place,`clip` can.
  34. dot = np.clip(np.einsum("ij,ij->i", vs, us), ls, out=vs[:, 0])
  35. # Projections.
  36. projs = vertices[:-1] + dot[:, None] * us
  37. ds = np.hypot(*(xy - projs).T, 1])
  38. try:
  39. argmin = np.nanargmin(ds)
  40. dmin = ds[argmin]
  41. except (ValueError, IndexError): # See above re: exceptions caught.
  42. return
  43. else:
  44. target = AttrArray(
  45. artist.axes.transData.inverted().transform_point(projs[argmin]))
  46. target.index = (
  47. (argmin + dot[argmin] / ls[argmin])
  48. / (path._interpolation_steps / tpath._interpolation_steps))
  49. return Selection(artist, dmin, None)
项目:mplcursors    作者:anntzer    | 项目源码 | 文件源码
  1. def _(artist, event):
  2. # No need to call `line.contains` because we''re going to redo
  3. # the work anyways (and it was broken for step plots up to
  4. # matplotlib/matplotlib#6645).
  5.  
  6. # Always work in screen coordinates,as this is how we need to compute
  7. # distances. Note that the artist transform may be different from the axes
  8. # transform (e.g.,for axvline).
  9. xy = event.x, event.y
  10. data_xy = artist.get_xydata()
  11. sels = []
  12. # If markers are visible,find the closest vertex.
  13. if artist.get_marker() not in ["None", "none", " ", "", None]:
  14. ds = np.hypot(*(xy - artist.get_transform().transform(data_xy)).T)
  15. try:
  16. argmin = np.nanargmin(ds)
  17. dmin = ds[argmin]
  18. except (ValueError, IndexError):
  19. # numpy 1.7.0''s `nanargmin([nan])` returns nan,so
  20. # `ds[argmin]` raises IndexError. In later versions of numpy,
  21. # `nanargmin([nan])` raises ValueError (the release notes for 1.8.0
  22. # are incorrect on this topic).
  23. pass
  24. else:
  25. # More precise than transforming back.
  26. target = with_attrs(artist.get_xydata()[argmin], index=argmin)
  27. sels.append(Selection(artist, None))
  28. # If lines are visible,find the closest projection.
  29. if (artist.get_linestyle() not in ["None", None]
  30. and len(artist.get_xydata()) > 1):
  31. sel = _compute_projection_pick(artist, artist.get_path(), xy)
  32. if sel is not None:
  33. sel.target.index = {
  34. "_draw_lines": lambda _, index: index,
  35. "_draw_steps_pre": Index.pre_index,
  36. "_draw_steps_mid": Index.mid_index,
  37. "_draw_steps_post": Index.post_index}[
  38. Line2D.drawStyles[artist.get_drawstyle()]](
  39. len(data_xy), sel.target.index)
  40. sels.append(sel)
  41. sel = min(sels, key=lambda sel: sel.dist, default=None)
  42. return sel if sel and sel.dist < artist.get_pickradius() else None
项目:orange-infrared    作者:markotoplak    | 项目源码 | 文件源码
  1. def mouseMoved(self, evt):
  2. pos = evt[0]
  3. if self.plot.sceneBoundingRect().contains(pos):
  4. mousePoint = self.plot.vb.mapScenetoView(pos)
  5. posx, posy = mousePoint.x(), mousePoint.y()
  6.  
  7. labels = []
  8. for a, vs in sorted(self.reports.items()):
  9. for v in vs:
  10. if isinstance(v, tuple) and len(v) == 2:
  11. if v[0] == "x":
  12. labels.append(("%0." + str(self.important_decimals[0]) + "f") % v[1])
  13. continue
  14. labels.append(str(v))
  15. labels = " ".join(labels)
  16. self.crosshair_hidden = bool(labels)
  17.  
  18. if self.location and not labels:
  19. fs = "%0." + str(self.important_decimals[0]) + "f %0." + str(self.important_decimals[1]) + "f"
  20. labels = fs % (posx, posy)
  21. self.label.setText(labels, color=(0, 0))
  22.  
  23. if self.curves and len(self.curves[0][0]): # need non-zero x axis!
  24. cache = {}
  25. bd = None
  26. if self.markclosest and self.plot.vb.action != ZOOMING:
  27. xpixel, ypixel = self.plot.vb.viewPixelSize()
  28. distances = distancetocurves(self.curves[0], posx, posy, xpixel, ypixel, r=self.MOUSE_RADIUS,
  29. cache=cache)
  30. try:
  31. mindi = np.nanargmin(distances)
  32. if distances[mindi] < self.MOUSE_RADIUS:
  33. bd = mindi
  34. except ValueError: # if all distances are NaN
  35. pass
  36. if self.highlighted != bd:
  37. QToolTip.hideText()
  38. if self.highlighted is not None and bd is None:
  39. self.highlighted = None
  40. self.highlighted_curve.hide()
  41. if bd is not None:
  42. self.highlighted = bd
  43. x = self.curves[0][0]
  44. y = self.curves[0][1][self.highlighted]
  45. self.highlighted_curve.setData(x=x, y=y)
  46. self.highlighted_curve.show()
  47.  
  48. self.vLine.setPos(posx)
  49. self.hLine.setPos(posy)
  50. self.viewhelpers_show()
  51. else:
  52. self.viewhelpers_hide()

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 模块-nanargmin() 实例源码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 ()、数组基本属性的相关知识,请在本站寻找。

本文标签: