您现在的位置是:网站首页> 编程资料编程资料
Numpy 数据处理 ndarray使用详解_python_
2023-05-25
294人已围观
简介 Numpy 数据处理 ndarray使用详解_python_
1. ndarray的属性
数组的属性反映了数组本身固有的信息。常用的查看数组属性的相关语法如下表格所示:
| 属性名称 | 属性解释 |
|---|---|
| ndarray.shape | 数组维度的元组 |
| ndarray.ndim | 数组维数 |
| ndarray.size | 数组中的元素数量 |
| ndarray.itemsize | 一个数组元素的长度(字节) |
| ndarray.dtype | 数组元素的类型 |
下面,我们将针对ndarray的各种属性,进行代码演示。
代码演示如下所示:
import numpy as np score = np.array([[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]]) print(score.shape) # 数组维度的元组 print(score.ndim) # 数组维数 print(score.size) # 数组中的元素数量 print(score.itemsize) # 一个数组元素的长度(字节) print(score.dtype) # 数组元素的类型
代码运行结果如下图所示:

注意:关于数组的维度,想知道数组有几维,最简单的办法就是看数组最外侧有多少个中括号,以上代码中传入的数组score有两个中括号,因此数组维数为2。
2. 数组的形状
关于数组形状,我们直接附上一段代码来理解:
c = np.array([[[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]], [[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]]]) print("c的数组维度:", c.shape) 以上代码运行结果如下图所示:

此处,输出的结果(2,4,3)(2,4,3)(2,4,3)的含义为:在最外层有2个二维数组。在二维数组里面,有4个一维数组。在一维数组里,有3个元素。
3. ndarray的类型
dtype是numpy.dtype类型,基本上之前所接触过的数据类型,这里面都支持。例如,bool、int32、int64、float32、uint8、complex64等等。
在我们创建array的同时是可以指定数组ndarray类型的。具体语法如下所示:
a = np.array([[[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]], [[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]]], dtype=np.float32) print(a.dtype) print(a)
代码运行结果如下图所示:可以发现结果中的数组元素带有小数点了。

当然,数组也可以存储字符串:
b = np.array(["python", "hello", "1"], dtype=np.string_) print(b)
运行结果如下图所示:

以上就是Numpy 数据处理 ndarray使用详解的详细内容,更多关于Numpy 数据处理 ndarray的资料请关注其它相关文章!
您可能感兴趣的文章:
相关内容
- 利用Pandas求两个dataframe差集的过程详解_python_
- Python NumPy教程之索引详解_python_
- Python NumPy教程之数据类型对象详解_python_
- Python selenium 八种定位元素的方式_python_
- Python requests.post()方法中data和json参数的使用方法_python_
- Python绘制牛奶冻曲线(高木曲线)案例_python_
- Python Pandas数据合并pd.merge用法详解_python_
- python第三方库pygame的使用详解_python_
- python groupby函数实现分组选取最大值与最小值_python_
- python操作SqlServer获取特定表的所有列名(推荐)_python_
