GVKun编程网logo

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

1

在本文中,我们将详细介绍Pythonnumpy模块-PINF实例源码的各个方面,并为您提供关于python中numpy模块的相关解答,同时,我们也将为您带来关于Jupyter中的Numpy在打印时出错

在本文中,我们将详细介绍Python numpy 模块-PINF 实例源码的各个方面,并为您提供关于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 模块-PINF 实例源码(python中numpy模块)

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

Python numpy 模块,PINF 实例源码

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

项目:pysptools    作者:ctherien    | 项目源码 | 文件源码
  1. def classify(fn, M, E):
  2. """
  3. Classify SAM or SID on a HSI cube
  4. Can''t be use with normXCorr
  5. """
  6. import pysptools.util as util
  7. width, height, bands = M.shape
  8. M = util.convert2d(M)
  9. cmap = np.zeros(M.shape[0])
  10. for i in range(M.shape[0]):
  11. T = M[i]
  12. floor = np.PINF
  13. k = 0
  14. for j in range(E.shape[0]):
  15. R = E[j]
  16. result = fn(T, R)
  17. if result < floor:
  18. floor = result
  19. k = j
  20. cmap[i] = k
  21. return util.convert3d(cmap, width, height)
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_adding_bin():
  2. col = ''mean radius''
  3. data = cancer_df[col].values
  4. cib = ConditionalInferenceBinner(''test_dim_{}''.format(col), alpha=0.95)
  5. cib.fit(data, cancer_target)
  6.  
  7. cib.add_bin(-1.0, [0.1, 0.9])
  8.  
  9. np.testing.assert_equal(cib.splits, [-1.0, 11.75, 13.079999923706055, 15.039999961853027, 16.84000015258789, np.PINF, np.NaN])
  10. np.testing.assert_equal(cib.values,
  11. [[0.1, 0.9],
  12. [0.02, 0.97999999999999998],
  13. [0.086956521739130432, 0.91304347826086951],
  14. [0.2878787878787879, 0.71212121212121215],
  15. [0.81481481481481477, 0.18518518518518517],
  16. [0.99152542372881358, 0.0084745762711864406],
  17. [0.37258347978910367, 0.62741652021089633]])
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_recursion_with_nan():
  2. col = ''mean area''
  3. data = cancer_df[col].values
  4. rand_idx = np.linspace(1, 500, 23).astype(int)
  5. data[rand_idx] = np.NaN
  6.  
  7. cib = ConditionalInferenceBinner(''test_dim_{}''.format(col), cancer_target)
  8.  
  9. np.testing.assert_equal(cib.splits, [471.29998779296875, 555.0999755859375, 693.7000122070312, 880.2000122070312,
  10. [[0.030769230769230771, 0.96923076923076923],
  11. [0.13414634146341464, 0.86585365853658536],
  12. [0.31730769230769229, 0.68269230769230771],
  13. [0.83333333333333337, 0.16666666666666666],
  14. [0.99145299145299148, 0.0085470085470085479],
  15. [0.2608695652173913, 0.73913043478260865]])
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_recursion_with_nan_and_special_value():
  2. col = ''mean area''
  3. data = cancer_df[col].values
  4. rand_idx = np.linspace(1, 23).astype(int)
  5. data[rand_idx] = np.NaN
  6.  
  7. rand_idx_2 = np.linspace(1, 550, 29).astype(int)
  8. data[rand_idx_2] = -1.0
  9.  
  10. cib = ConditionalInferenceBinner(''test_dim_{}''.format(col), alpha=0.95, special_values=[-1.0, np.NaN])
  11. cib.fit(data, 471.29998779296875, 572.2999877929688, 819.7999877929688,
  12. [[0.4827586206896552, 0.5172413793103449],
  13. [0.032432432432432434, 0.9675675675675676],
  14. [0.14432989690721648, 0.8556701030927835],
  15. [0.3132530120481928, 0.6867469879518072],
  16. [0.8205128205128205, 0.1794871794871795],
  17. [1.0, 0.0],
  18. [0.23809523809523808, 0.7619047619047619]])
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def _init_shapes_and_data(self, data, labels):
  2.  
  3. self.n_features = data.shape[1]
  4.  
  5. if isinstance(data, pandas.core.frame.DataFrame):
  6. self.feature_names = data.columns.tolist()
  7. data = data.as_matrix()
  8.  
  9. if self.feature_names is None:
  10. self.feature_names = [''feature_{}''.format(dim) for dim in range(self.n_features)]
  11.  
  12. if isinstance(labels, pandas.core.series.Series):
  13. labels = labels.values
  14.  
  15. cntr = Counter(labels)
  16. assert set(cntr.keys()) == {-1, 1}, "Labels must be encoded with -1,1. Cannot contain more classes."
  17. assert self.n_features is not None, "Number of attributes is None"
  18.  
  19. self.shapes = {name: ShapeFunction([np.PINF],
  20. [0.0],
  21. name)
  22. for name in self.feature_names}
  23. self.initialized = True
  24.  
  25. return data, labels
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def _recurse_tree(tree, lst, mdlp, node_id=0, depth=0, min_val=np.NINF, max_val=np.PINF):
  2. left_child = tree.children_left[node_id]
  3. right_child = tree.children_right[node_id]
  4.  
  5. if left_child == sklearn.tree._tree.TREE_LEAF:
  6. lst.append(((min_val, max_val), tree.value[node_id].flatten().tolist()))
  7. return
  8. else:
  9. if mdlp and _check_mdlp_stop(tree, node_id):
  10. lst.append(((min_val, tree.value[node_id].flatten().tolist()))
  11. return
  12. _recurse_tree(tree, left_child, depth=depth + 1, min_val=min_val, max_val=tree.threshold[node_id])
  13.  
  14. if right_child == sklearn.tree._tree.TREE_LEAF:
  15. lst.append(((min_val, right_child, min_val=tree.threshold[node_id], max_val=max_val)
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def _clipper(self):
  2. ''''''
  3. projects the weights to the feasible set
  4. :return:
  5. ''''''
  6. return tf.assign(self.W, tf.clip_by_value(self.W, 0, np.PINF), name="projector")
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def _create_partition(lst_of_splits):
  2. return np.append(lst_of_splits, np.PINF)
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_func_add_2():
  2. func1 = ShapeFunction([np.PINF], [0], ''test_1'')
  3. func2 = ShapeFunction([0, 1, 2], [-1, -2], ''test_1'')
  4.  
  5. assert func1 != func2
  6.  
  7. func3 = ShapeFunction([0.0, 1.0, 2.0, np.PINF],
  8. [-1.0, -2.0, ''test_1'')
  9.  
  10. assert func1.add(func2).equals(func3)
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_recursion():
  2. binner = tfb.DecisionTreeBinner(''test'', max_leaf_nodes=4)
  3. binner.fit(data[:, 0], target)
  4.  
  5. np.testing.assert_equal(binner.splits, [13.094999313354492, 15.045000076293945, 16.924999237060547, np.NaN])
  6. np.testing.assert_equal(binner.values, [[0.04905660377358491, 0.9509433962264151],
  7. [0.2878787878787879, 0.7121212121212122],
  8. [0.8148148148148148,
  9. [0.9915254237288136, 0.00847457627118644],
  10. [0.37258347978910367, 0.62741652021089633]])
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_recursion_with_mdlp():
  2. binner = tfb.DecisionTreeBinner(''test'', mdlp=True)
  3. binner.fit(data[:, 17.880001068115234,
  4. [0.8533333333333334, 0.14666666666666667],
  5. [1.0, 0.62741652021089633]])
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_recursion():
  2. col = ''mean radius''
  3. data = cancer_df[col].values
  4. cib = ConditionalInferenceBinner(''test_dim_{}''.format(col), [11.75,
  5. [[0.02, 0.62741652021089633]])
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def test_adding_bin_with_non_numeric_splits_only():
  2. cib = ConditionalInferenceBinner(''test'', alpha=0.05)
  3. cib.splits = [np.PINF, np.NaN]
  4. cib.values = [[0.1, [0.8, 0.2]]
  5. cib.is_fit = True
  6.  
  7. cib.add_bin(-1.0, [0.3, 0.7])
  8. np.testing.assert_equal(cib.splits, [[0.3, 0.7], 0.2]])
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def __init__(self, name, **kwargs):
  2. self.name = name
  3.  
  4. self.alpha = kwargs.get(''alpha'', 0.95)
  5. self.min_samples_split = kwargs.get(''min_samples_split'', 2)
  6. self.min_samples_leaf = kwargs.get(''min_samples_leaf'', 2)
  7. self.special_values = kwargs.get(''special_values'', [np.NaN])
  8.  
  9. self.num_classes = None
  10.  
  11. self._splits = [np.PINF]
  12. self._values = list()
  13. self.nodes = list()
  14.  
  15. self._is_fit = False
项目:dstk    作者:jotterbach    | 项目源码 | 文件源码
  1. def __init__(self, **kwargs):
  2. self.name = name
  3. self._is_fit = False
  4.  
  5. criterion = kwargs.get(''criterion'', ''gini'')
  6. splitter = kwargs.get(''splitter'', ''best'')
  7. max_depth = kwargs.get(''max_depth'', None)
  8. min_samples_split = kwargs.get(''min_samples_split'', 2)
  9. min_samples_leaf = kwargs.get(''min_samples_leaf'', 1)
  10. min_weight_fraction_leaf = kwargs.get(''min_weight_fraction_leaf'', 0.0)
  11. max_features = kwargs.get(''max_features'', None)
  12. random_state = kwargs.get(''random_state'', None)
  13. max_leaf_nodes = kwargs.get(''max_leaf_nodes'', None)
  14. class_weight = kwargs.get(''class_weight'', None)
  15. presort = kwargs.get(''presort'', False)
  16.  
  17. self.mdlp = kwargs.get(''mdlp'', False)
  18.  
  19. if self.mdlp:
  20. criterion = ''entropy''
  21. max_leaf_nodes = None
  22. max_depth = None
  23.  
  24. self.dtc = DecisionTreeClassifier(criterion=criterion,
  25. splitter=splitter,
  26. max_depth=max_depth,
  27. min_samples_split=min_samples_split,
  28. min_samples_leaf=min_samples_leaf,
  29. min_weight_fraction_leaf=min_weight_fraction_leaf,
  30. max_features=max_features,
  31. random_state=random_state,
  32. max_leaf_nodes=max_leaf_nodes,
  33. class_weight=class_weight,
  34. presort=presort)
  35.  
  36. self._splits = [np.PINF]
  37. self._values = list()
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def masked_invalid(a, copy=True):
  2. """
  3. Mask an array where invalid values occur (NaNs or infs).
  4.  
  5. This function is a shortcut to ``masked_where``,with
  6. `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
  7. Only applies to arrays with a dtype where NaNs or infs make sense
  8. (i.e. floating point types),but accepts any array_like object.
  9.  
  10. See Also
  11. --------
  12. masked_where : Mask where a condition is met.
  13.  
  14. Examples
  15. --------
  16. >>> import numpy.ma as ma
  17. >>> a = np.arange(5,dtype=np.float)
  18. >>> a[2] = np.NaN
  19. >>> a[3] = np.PINF
  20. >>> a
  21. array([ 0.,1.,NaN,Inf,4.])
  22. >>> ma.masked_invalid(a)
  23. masked_array(data = [0.0 1.0 -- -- 4.0],
  24. mask = [False False True True False],
  25. fill_value=1e+20)
  26.  
  27. """
  28. a = np.array(a, copy=copy, subok=True)
  29. mask = getattr(a, ''_mask'', None)
  30. if mask is not None:
  31. condition = ~(np.isfinite(getdata(a)))
  32. if mask is not nomask:
  33. condition |= mask
  34. cls = type(a)
  35. else:
  36. condition = ~(np.isfinite(a))
  37. cls = MaskedArray
  38. result = a.view(cls)
  39. result._mask = condition
  40. return result
  41.  
  42.  
  43. ###############################################################################
  44. # Printing options #
  45. ###############################################################################
项目:pandas-profiling    作者:JosPolfliet    | 项目源码 | 文件源码
  1. def describe_1d(data, **kwargs):
  2. leng = len(data) # number of observations in the Series
  3. count = data.count() # number of non-NaN observations in the Series
  4.  
  5. # Replace infinite values with NaNs to avoid issues with
  6. # histograms later.
  7. data.replace(to_replace=[np.inf, np.NINF, value=np.nan, inplace=True)
  8.  
  9. n_infinite = count - data.count() # number of infinte observations in the Series
  10.  
  11. distinct_count = data.nunique(dropna=False) # number of unique elements in the Series
  12. if count > distinct_count > 1:
  13. mode = data.mode().iloc[0]
  14. else:
  15. mode = data[0]
  16.  
  17. results_data = {''count'': count,
  18. ''distinct_count'': distinct_count,
  19. ''p_missing'': 1 - count / leng,
  20. ''n_missing'': leng - count,
  21. ''p_infinite'': n_infinite / leng,
  22. ''n_infinite'': n_infinite,
  23. ''is_unique'': distinct_count == leng,
  24. ''mode'': mode,
  25. ''p_unique'': distinct_count / leng}
  26. try:
  27. # pandas 0.17 onwards
  28. results_data[''memorysize''] = data.memory_usage()
  29. except:
  30. results_data[''memorysize''] = 0
  31.  
  32. result = pd.Series(results_data, name=data.name)
  33.  
  34. vartype = get_vartype(data)
  35. if vartype == ''CONST'':
  36. result = result.append(describe_constant_1d(data))
  37. elif vartype == ''BOOL'':
  38. result = result.append(describe_boolean_1d(data, **kwargs))
  39. elif vartype == ''NUM'':
  40. result = result.append(describe_numeric_1d(data, **kwargs))
  41. elif vartype == ''DATE'':
  42. result = result.append(describe_date_1d(data, **kwargs))
  43. elif vartype == ''UNIQUE'':
  44. result = result.append(describe_unique_1d(data, **kwargs))
  45. else:
  46. result = result.append(describe_categorical_1d(data))
  47. return result
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def masked_invalid(a, None)
  2. if mask is not None:
  3. condition = ~(np.isfinite(getdata(a)))
  4. if mask is not nomask:
  5. condition |= mask
  6. cls = type(a)
  7. else:
  8. condition = ~(np.isfinite(a))
  9. cls = MaskedArray
  10. result = a.view(cls)
  11. result._mask = condition
  12. return result
  13.  
  14.  
  15. ###############################################################################
  16. # Printing options #
  17. ###############################################################################
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def masked_invalid(a, None)
  2. if mask is not None:
  3. condition = ~(np.isfinite(getdata(a)))
  4. if mask is not nomask:
  5. condition |= mask
  6. cls = type(a)
  7. else:
  8. condition = ~(np.isfinite(a))
  9. cls = MaskedArray
  10. result = a.view(cls)
  11. result._mask = condition
  12. return result
  13.  
  14.  
  15. ###############################################################################
  16. # Printing options #
  17. ###############################################################################
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def masked_invalid(a, None)
  2. if mask is not None:
  3. condition = ~(np.isfinite(getdata(a)))
  4. if mask is not nomask:
  5. condition |= mask
  6. cls = type(a)
  7. else:
  8. condition = ~(np.isfinite(a))
  9. cls = MaskedArray
  10. result = a.view(cls)
  11. result._mask = condition
  12. return result
  13.  
  14.  
  15. ###############################################################################
  16. # Printing options #
  17. ###############################################################################
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def masked_invalid(a, None)
  2. if mask is not None:
  3. condition = ~(np.isfinite(getdata(a)))
  4. if mask is not nomask:
  5. condition |= mask
  6. cls = type(a)
  7. else:
  8. condition = ~(np.isfinite(a))
  9. cls = MaskedArray
  10. result = a.view(cls)
  11. result._mask = condition
  12. return result
  13.  
  14.  
  15. ###############################################################################
  16. # Printing options #
  17. ###############################################################################
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def masked_invalid(a, None)
  2. if mask is not None:
  3. condition = ~(np.isfinite(getdata(a)))
  4. if mask is not nomask:
  5. condition |= mask
  6. cls = type(a)
  7. else:
  8. condition = ~(np.isfinite(a))
  9. cls = MaskedArray
  10. result = a.view(cls)
  11. result._mask = condition
  12. return result
  13.  
  14.  
  15. ###############################################################################
  16. # Printing options #
  17. ###############################################################################
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def masked_invalid(a, None)
  2. if mask is not None:
  3. condition = ~(np.isfinite(getdata(a)))
  4. if mask is not nomask:
  5. condition |= mask
  6. cls = type(a)
  7. else:
  8. condition = ~(np.isfinite(a))
  9. cls = MaskedArray
  10. result = a.view(cls)
  11. result._mask = condition
  12. return result
  13.  
  14.  
  15. ###############################################################################
  16. # Printing options #
  17. ###############################################################################

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

本文标签: