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