GVKun编程网logo

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

6

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

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

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

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

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

项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def _nanpercentile(a, q, axis=None, out=None, overwrite_input=False,
  2. interpolation=''linear'', keepdims=False):
  3. """
  4. Private function that doesn''t support extended axis or keepdims.
  5. These methods are extended to this function using _ureduce
  6. See nanpercentile for parameter usage
  7.  
  8. """
  9. if axis is None:
  10. part = a.ravel()
  11. result = _nanpercentile1d(part, overwrite_input, interpolation)
  12. else:
  13. result = np.apply_along_axis(_nanpercentile1d, axis, a,
  14. overwrite_input, interpolation)
  15. # apply_along_axis fills in collapsed axis with results.
  16. # Move that axis to the beginning to match percentile''s
  17. # convention.
  18. if q.ndim != 0:
  19. result = np.rollaxis(result, axis)
  20.  
  21. if out is not None:
  22. out[...] = result
  23. return result
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_out(self):
  2. mat = np.random.rand(3, 3)
  3. nan_mat = np.insert(mat, [0, 2], np.nan, axis=1)
  4. resout = np.zeros(3)
  5. tgt = np.percentile(mat, 42, axis=1)
  6. res = np.nanpercentile(nan_mat, axis=1, out=resout)
  7. assert_almost_equal(res, resout)
  8. assert_almost_equal(res, tgt)
  9. # 0-d output:
  10. resout = np.zeros(())
  11. tgt = np.percentile(mat, axis=None)
  12. res = np.nanpercentile(nan_mat, tgt)
  13. res = np.nanpercentile(nan_mat, axis=(0, 1), tgt)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_allnans(self):
  2. mat = np.array([np.nan]*9).reshape(3, 3)
  3. for axis in [None, 0, 1]:
  4. with warnings.catch_warnings(record=True) as w:
  5. warnings.simplefilter(''always'')
  6. assert_(np.isnan(np.nanpercentile(mat, 60, axis=axis)).all())
  7. if axis is None:
  8. assert_(len(w) == 1)
  9. else:
  10. assert_(len(w) == 3)
  11. assert_(issubclass(w[0].category, RuntimeWarning))
  12. # Check scalar
  13. assert_(np.isnan(np.nanpercentile(np.nan, 60)))
  14. if axis is None:
  15. assert_(len(w) == 2)
  16. else:
  17. assert_(len(w) == 4)
  18. assert_(issubclass(w[0].category, RuntimeWarning))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_multiple_percentiles(self):
  2. perc = [50, 100]
  3. mat = np.ones((4, 3))
  4. nan_mat = np.nan * mat
  5. # For checking consistency in higher dimensional case
  6. large_mat = np.ones((3, 4, 5))
  7. large_mat[:, 0:2:4, :] = 0
  8. large_mat[:, :, 3:] *= 2
  9. for axis in [None, 1]:
  10. for keepdim in [False, True]:
  11. with warnings.catch_warnings(record=True) as w:
  12. warnings.simplefilter(''always'')
  13. val = np.percentile(mat, perc, axis=axis, keepdims=keepdim)
  14. nan_val = np.nanpercentile(nan_mat,
  15. keepdims=keepdim)
  16. assert_equal(nan_val.shape, val.shape)
  17.  
  18. val = np.percentile(large_mat,
  19. keepdims=keepdim)
  20. nan_val = np.nanpercentile(large_mat,
  21. keepdims=keepdim)
  22. assert_equal(nan_val, val)
  23.  
  24. megamat = np.ones((3, 5, 6))
  25. assert_equal(np.nanpercentile(megamat, axis=(1, 2)).shape, (2, 3, 6))
项目:psp    作者:cmap    | 项目源码 | 文件源码
  1. def convert_percentile_to_thresh(g, percentile):
  2. """ figure out what value in g corresponds to the given percentile.
  3.  
  4. Args:
  5. @param g:
  6. @type g: igraph.Graph
  7. @param percentile: between 0 and 100
  8. @type percentile: float
  9.  
  10. Returns:
  11. thresh
  12.  
  13. """
  14. assert percentile < 100 and percentile > 0, (
  15. "percentile must be between 0 and 100. percentile: {}".format(percentile))
  16.  
  17. thresh = np.nanpercentile(np.abs(g.es["weight"]), percentile)
  18.  
  19. return thresh
项目:scipyplot    作者:robertocalandra    | 项目源码 | 文件源码
  1. def median_percentile(data, des_percentiles=''68+95+99''):
  2. """
  3.  
  4. :param data:
  5. :param des_percentiles: string with +separated values of the percentiles
  6. :return:
  7. """
  8. median = np.nanmedian(data, axis=0)
  9. out = np.array(map(int, des_percentiles.split("+")))
  10. for i in range(out.size):
  11. assert 0 <= out[i] <= 100, ''percentile must be >0 <100; instead is %f'' % out[i]
  12. list_percentiles = np.empty((2*out.size,), dtype=out.dtype)
  13. list_percentiles[0::2] = out # Compute the percentile
  14. list_percentiles[1::2] = 100 - out # Compute also the mirror percentile
  15. percentiles = np.nanpercentile(data, list_percentiles, axis=0)
  16. return [median, percentiles]
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def _nanpercentile(a, axis)
  2.  
  3. if out is not None:
  4. out[...] = result
  5. return result
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_out(self):
  2. mat = np.random.rand(3, tgt)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_allnans(self):
  2. mat = np.array([np.nan]*9).reshape(3, RuntimeWarning))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_multiple_percentiles(self):
  2. perc = [50, 6))
项目:mimclib    作者:stochasticNumerics    | 项目源码 | 文件源码
  1. def plottimeVsLvls(ax, runs, *args, **kwargs):
  2. """Plots Time vs TOL of @runs,as
  3. returned by MIMCDatabase.readRunData()
  4. ax is in instance of matplotlib.axes
  5. """
  6. ax.set_xlabel(r''$\\ell$'')
  7. ax.set_ylabel(''Time (s)'')
  8. ax.set_yscale(''log'')
  9. fnnorm = kwargs.pop("fnnorm")
  10. if "__calc_moments" in kwargs:
  11. _, _, Tl, M, _ = kwargs.pop("__calc_moments")
  12. else:
  13. _, _ = __calc_moments(runs,
  14. seed=kwargs.pop(''seed'', None),
  15. direction=kwargs.pop(''direction'', fnnorm=fnnorm)
  16. ax.xaxis.set_major_locator(MaxNLocator(integer=True))
  17.  
  18. min_tl = np.nanpercentile(Tl, axis=1)
  19. med = np.nanmean(Tl, axis=1)
  20. max_tl = np.nanpercentile(Tl, 95, axis=1)
  21. line = ax.errorbar(np.arange(0, len(Tl)),
  22. med, yerr=[med-min_tl, max_tl-med],
  23. *args, **kwargs)
  24. return line[0].get_xydata(), [line]
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def _nanpercentile(a, interpolation)
  2.  
  3. if out is not None:
  4. out[...] = result
  5. return result
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_out(self):
  2. mat = np.random.rand(3, tgt)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_allnans(self):
  2. mat = np.array([np.nan]*9).reshape(3, RuntimeWarning))
项目:prophet    作者:facebook    | 项目源码 | 文件源码
  1. def predict_uncertainty(self, df):
  2. """Prediction intervals for yhat and trend.
  3.  
  4. Parameters
  5. ----------
  6. df: Prediction dataframe.
  7.  
  8. Returns
  9. -------
  10. Dataframe with uncertainty intervals.
  11. """
  12. sim_values = self.sample_posterior_predictive(df)
  13.  
  14. lower_p = 100 * (1.0 - self.interval_width) / 2
  15. upper_p = 100 * (1.0 + self.interval_width) / 2
  16.  
  17. series = {}
  18. for key in [''yhat'', ''trend'']:
  19. series[''{}_lower''.format(key)] = np.nanpercentile(
  20. sim_values[key], lower_p, axis=1)
  21. series[''{}_upper''.format(key)] = np.nanpercentile(
  22. sim_values[key], upper_p, axis=1)
  23.  
  24. return pd.DataFrame(series)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def _nanpercentile(a,
  2. interpolation=''linear''):
  3. """
  4. Private function that doesn''t support extended axis or keepdims.
  5. These methods are extended to this function using _ureduce
  6. See nanpercentile for parameter usage
  7.  
  8. """
  9. if axis is None:
  10. part = a.ravel()
  11. result = _nanpercentile1d(part, axis)
  12.  
  13. if out is not None:
  14. out[...] = result
  15. return result
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_out(self):
  2. mat = np.random.rand(3, tgt)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_allnans(self):
  2. mat = np.array([np.nan]*9).reshape(3, RuntimeWarning))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_multiple_percentiles(self):
  2. perc = [50, 6))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def _nanpercentile(a,
  2. interpolation=''linear''):
  3. """
  4. Private function that doesn''t support extended axis or keepdims.
  5. These methods are extended to this function using _ureduce
  6. See nanpercentile for parameter usage
  7.  
  8. """
  9. if axis is None or a.ndim == 1:
  10. part = a.ravel()
  11. result = _nanpercentile1d(part, axis)
  12.  
  13. if out is not None:
  14. out[...] = result
  15. return result
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_out(self):
  2. mat = np.random.rand(3, tgt)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_allnans(self):
  2. mat = np.array([np.nan]*9).reshape(3, RuntimeWarning))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_multiple_percentiles(self):
  2. perc = [50, True]:
  3. with suppress_warnings() as sup:
  4. sup.filter(RuntimeWarning, "All-NaN slice encountered")
  5. val = np.percentile(mat, 6))
项目:rio-cloudmask    作者:mapBox    | 项目源码 | 文件源码
  1. def temp_water(is_water, swir2, tirs1):
  2. """Use water to mask tirs and find 82.5 pctile
  3.  
  4. Equation 7 and 8 (Zhu and Woodcock,2012)
  5.  
  6. Parameters
  7. ----------
  8. is_water: ndarray,boolean
  9. water mask,water is True,land is False
  10. swir2: ndarray
  11. tirs1: ndarray
  12.  
  13. Output
  14. ------
  15. float:
  16. 82.5th percentile temperature over water
  17. """
  18. # eq7
  19. th_swir2 = 0.03
  20. clearsky_water = is_water & (swir2 < th_swir2)
  21.  
  22. # eq8
  23. clear_water_temp = tirs1.copy()
  24. clear_water_temp[~clearsky_water] = np.nan
  25. return np.nanpercentile(clear_water_temp, 82.5)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def _nanpercentile(a, axis)
  2.  
  3. if out is not None:
  4. out[...] = result
  5. return result
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_out(self):
  2. mat = np.random.rand(3, tgt)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_allnans(self):
  2. mat = np.array([np.nan]*9).reshape(3, RuntimeWarning))
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_multiple_percentiles(self):
  2. perc = [50, 6))
项目:agdc_statistics    作者:GeoscienceAustralia    | 项目源码 | 文件源码
  1. def test_nan_percentile():
  2. # create array of shape(5,100,100) - image of size 100x100 with 5 layers
  3. test_arr = np.random.randint(0, 10000, 50000).reshape(5, 100, 100).astype(np.float32)
  4. np.random.shuffle(test_arr)
  5. # place random NaNs
  6. random_nans = np.random.randint(0, 50000, 500).astype(np.float32)
  7. for r in random_nans:
  8. test_arr[test_arr == r] = np.NaN
  9.  
  10. # Test with single q
  11. q = 45
  12. input_arr = np.array(test_arr, copy=True)
  13. std_np_func = np.nanpercentile(input_arr, q=q, axis=0)
  14. new_func = nan_percentile(input_arr, q=q)
  15.  
  16. assert np.allclose(std_np_func, new_func)
  17.  
  18. # Test with all qs
  19. qs = range(0, 100)
  20. input_arr = np.array(test_arr, q=qs, q=qs)
  21.  
  22. assert np.allclose(std_np_func, new_func)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def _nanpercentile1d(arr1d, interpolation=''linear''):
  2. """
  3. Private function for rank 1 arrays. Compute percentile ignoring
  4. NaNs.
  5.  
  6. See nanpercentile for parameter usage
  7. """
  8. c = np.isnan(arr1d)
  9. s = np.where(c)[0]
  10. if s.size == arr1d.size:
  11. warnings.warn("All-NaN slice encountered", RuntimeWarning)
  12. if q.ndim == 0:
  13. return np.nan
  14. else:
  15. return np.nan * np.ones((len(q),))
  16. elif s.size == 0:
  17. return np.percentile(arr1d, overwrite_input=overwrite_input,
  18. interpolation=interpolation)
  19. else:
  20. if overwrite_input:
  21. x = arr1d
  22. else:
  23. x = arr1d.copy()
  24. # select non-nans at end of array
  25. enonan = arr1d[-s.size:][~c[-s.size:]]
  26. # fill nans in beginning of array with non-nans of end
  27. x[s[:enonan.size]] = enonan
  28. # slice nans away
  29. return np.percentile(x[:-s.size], overwrite_input=True,
  30. interpolation=interpolation)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_mutation(self):
  2. # Check that passed array is not modified.
  3. ndat = _ndat.copy()
  4. np.nanpercentile(ndat, 30)
  5. assert_equal(ndat, _ndat)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_keepdims(self):
  2. mat = np.eye(3)
  3. for axis in [None, 1]:
  4. tgt = np.percentile(mat, 70,
  5. overwrite_input=False)
  6. res = np.nanpercentile(mat,
  7. overwrite_input=False)
  8. assert_(res.ndim == tgt.ndim)
  9.  
  10. d = np.ones((3, 7, 11))
  11. # Randomly set some elements to NaN:
  12. w = np.random.random((4, 200)) * np.array(d.shape)[:, None]
  13. w = w.astype(np.intp)
  14. d[tuple(w)] = np.nan
  15. with warnings.catch_warnings(record=True) as w:
  16. warnings.simplefilter(''always'', RuntimeWarning)
  17. res = np.nanpercentile(d, 90, keepdims=True)
  18. assert_equal(res.shape, (1, 1, 1))
  19. res = np.nanpercentile(d, 11))
  20. res = np.nanpercentile(d, 3), (3, 2, 1))
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_empty(self):
  2. mat = np.zeros((0, 3))
  3. for axis in [0, None]:
  4. with warnings.catch_warnings(record=True) as w:
  5. warnings.simplefilter(''always'')
  6. assert_(np.isnan(np.nanpercentile(mat, 40, axis=axis)).all())
  7. assert_(len(w) == 1)
  8. assert_(issubclass(w[0].category, RuntimeWarning))
  9. for axis in [1]:
  10. with warnings.catch_warnings(record=True) as w:
  11. warnings.simplefilter(''always'')
  12. assert_equal(np.nanpercentile(mat, axis=axis), np.zeros([]))
  13. assert_(len(w) == 0)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_scalar(self):
  2. assert_(np.nanpercentile(0., 100) == 0.)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_extended_axis_invalid(self):
  2. d = np.ones((3, 11))
  3. assert_raises(IndexError, np.nanpercentile, d, q=5, axis=-5)
  4. assert_raises(IndexError, -5))
  5. assert_raises(IndexError, axis=4)
  6. assert_raises(IndexError, 4))
  7. assert_raises(ValueError, 1))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def _nanpercentile1d(arr1d,
  2. interpolation=interpolation)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_mutation(self):
  2. # Check that passed array is not modified.
  3. ndat = _ndat.copy()
  4. np.nanpercentile(ndat, _ndat)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_keepdims(self):
  2. mat = np.eye(3)
  3. for axis in [None, 1))
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_empty(self):
  2. mat = np.zeros((0, np.zeros([]))
  3. assert_(len(w) == 0)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_scalar(self):
  2. assert_(np.nanpercentile(0., 100) == 0.)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_extended_axis_invalid(self):
  2. d = np.ones((3, 1))
项目:nanslice    作者:spinicist    | 项目源码 | 文件源码
  1. def interactive(img, cmap=''gray'', window=(2, 98)):
  2. import ipywidgets as ipy
  3.  
  4. # Get some information about the image
  5. bBox = Box.fromMask(img)
  6. window_vals = np.nanpercentile(img.get_data(), window)
  7. # Setup figure
  8. fig, axes = plt.subplots(1, figsize=(8, 4))
  9. implots = [None, None, None]
  10. for i in range(3):
  11. sl = Slice(bBox, bBox.center, i, 256, orient=''clin'')
  12. sl_img = sl.sample(img, order=0)
  13. sl_color = colorize(sl_img, cmap, window_vals)
  14. implots[i] = axes[i].imshow(sl_color, origin=''lower'', extent=sl.extent, cmap=cmap, vmin = 0.1)
  15. axes[i].axis(''off'')
  16.  
  17. def wrap_sections(x, y, z):
  18. for i in range(3):
  19. sl = Slice(bBox, np.array((x, z)), orient=''clin'')
  20. sl_img = sl.sample(img, order=0)
  21. sl_color = colorize(sl_img, window_vals)
  22. implots[i].set_data(sl_color)
  23. plt.show()
  24.  
  25. # Setup widgets
  26. slider_x = ipy.FloatSlider(min=bBox.start[0], max=bBox.end[0], value=bBox.center[0])
  27. slider_y = ipy.FloatSlider(min=bBox.start[1], max=bBox.end[1], value=bBox.center[1])
  28. slider_z = ipy.FloatSlider(min=bBox.start[2], max=bBox.end[2], value=bBox.center[2])
  29. widgets = ipy.interactive(wrap_sections, x=slider_x, y=slider_y, z=slider_z)
  30.  
  31. # Now do some manual layout
  32. hBox = ipy.HBox(widgets.children[0:3]) # Set the sliders to horizontal layout
  33. vBox = ipy.VBox((hBox, widgets.children[3]))
  34. # iplot.widget.children[-1].layout.height = ''350px''
  35. return vBox
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def plot_aligned(data_all, transitions, label = ''data'', dt = time_bin, phase = 0):
  2. phase_names = [''hatch'', ''L1'', ''L2'', ''L3'', ''L4'', ''L5''];
  3.  
  4. ttref0 = np.max(transitions[:, 0]);
  5. ntt = data_all.shape[1] + ttref0 + 500;
  6. nw = data_all.shape[0];
  7.  
  8. tr = phase;
  9. data_algn = np.zeros((nw, ntt));
  10. tref = np.max(transitions[:, tr]);
  11. for wid in range(nworms):
  12. tt = transitions[wid, tr];
  13. ts = transitions[wid, 0];
  14. te = transitions[wid, -1];
  15. nt = te - ts;
  16. t0 = ts + tref - tt;
  17. t1 = t0 + nt;
  18. #print ''tref=%s,ts =%d,te=%d,tt =%d,nt = %d,t0=%d,t1=%d,ntt=%d'' % (tref,ts,te,tt,nt,t0,t1,ntt)
  19. data_algn[wid, t0 : t1] = data_all[wid, ts:te];
  20.  
  21. #rmax = np.nanpercentile(roam_24hr,95);
  22. rmax = 1;
  23. plt.imshow(data_algn, interpolation = ''none'', aspect = ''auto'', cmap = plt.cm.viridis, vmax = rmax )
  24. cb = plt.colorbar(fraction = 0.025, shrink = 0.5, pad = 0.01)
  25. cb.ax.set_ylabel(label + '' [au]'', rotation=270, labelpad = 20)
  26.  
  27. days = np.array(24. * 60 * 60 / time_bin * np.arange(6), dtype = int);
  28. labl = [''%d''%d for d in 24 *np.linspace(0,5, 6)];
  29. plt.xticks(days, labl);
  30. plt.xlabel(''time [hrs]'');
  31. plt.ylabel(''worm id'');
  32. plt.tight_layout()
  33.  
  34. plt.title(phase_names[tr]);
  35. plt.tight_layout()
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def plot_aligned(data_all, labl);
  2. plt.xlabel(''time [hrs]'');
  3. plt.ylabel(''worm id'');
  4. plt.tight_layout()
  5.  
  6. plt.title(phase_names[tr]);
  7. plt.tight_layout()
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def plot_aligned(data_all, labl);
  2. plt.xlabel(''time [hrs]'');
  3. plt.ylabel(''worm id'');
  4. plt.tight_layout()
  5.  
  6. plt.title(phase_names[tr]);
  7. plt.tight_layout()
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def plot_aligned(data_all, labl);
  2. plt.xlabel(''time [hrs]'');
  3. plt.ylabel(''worm id'');
  4. plt.tight_layout()
  5.  
  6. plt.title(phase_names[tr]);
  7. plt.tight_layout()
项目:CElegansBehavIoUr    作者:ChristophKirst    | 项目源码 | 文件源码
  1. def plot_aligned(data_all, labl);
  2. plt.xlabel(''time [hrs]'');
  3. plt.ylabel(''worm id'');
  4. plt.tight_layout()
  5.  
  6. plt.title(phase_names[tr]);
  7. plt.tight_layout()
项目:zalpha    作者:fred-hz    | 项目源码 | 文件源码
  1. def downstddv(x):
  2. if x.size < 4:
  3. return np.nan
  4. median = np.nanpercentile(x, 50)
  5. return np.nanstd(x[x < median])
项目:mimclib    作者:stochasticNumerics    | 项目源码 | 文件源码
  1. def __get_stats(data, groupby=0, staton=1):
  2. import itertools
  3. data = sorted(data, key=lambda xx: xx[groupby])
  4. x = []
  5. y = []
  6. for k, itr in itertools.groupby(data, key=lambda xx: xx[groupby]):
  7. all_y = [d[staton] for d in itr]
  8. y.append([np.nanpercentile(all_y, 5),
  9. np.nanpercentile(all_y, 50), 95)])
  10. x.append(k)
  11. return np.array(x), np.array(y)
项目:pyphot    作者:mfouesneau    | 项目源码 | 文件源码
  1. def p16(s, v):
  2. try:
  3. return np.nanpercentile(v, 16)
  4. except AttributeError:
  5. return np.percentile(v, 16)

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 模块-nanpercentile() 实例源码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 ()、数组基本属性的相关信息,请在本站查询。

本文标签: