numpy数组的属性

本文详细介绍了NumPy数组的基本属性,包括维度(ndim)、形状(shape)、元素个数(size)、数据类型(dtype)、每个元素占用的内存大小(itemsize)及数组总内存大小(nbytes)。通过实例展示了如何使用这些属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

numpy数组的属性

个人学习笔记,分享给大家!

numpy数组属性:ndim,shape,size,dtype,itemsize,nbytes

import numpy as np
#numpy数组属性:ndim,shape,size,dtype,itemsize,nbytes
x = np.eye(5)
x
Out[2]:

array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.]])

x.ndim#数组的维度
Out[3]:

2
x.shape#数组的形状
Out[4]:

(5, 5)

x.size#数组的元素个数
Out[5]:

25

x.dtype#数组的数据类型
Out[6]:

dtype('float64')

x.itemsize#数组的每个元素占用的内存大小,以字节为单位
Out[7]:

8

x.nbytes#数组占用的总内存大小,以字节为单位
Out[8]:

200

### Numpy 数组的使用方法与示例教程 Numpy 是 Python 中用于数值计算的核心库,其核心功能是对多维数组的支持。以下是关于 Numpy 数组的一些基本概念和常见操作。 #### 创建 Numpy 数组 可以通过多种方式创建 Numpy 数组,常见的有 `np.array` 和其他专用函数如 `np.zeros`, `np.ones`, 或者从已有的列表转换而来[^2]。 ```python import numpy as np # 从列表创建数组 arr_from_list = np.array([1, 2, 3]) # 创建全零矩阵 zeros_matrix = np.zeros((3, 4)) # 创建全一矩阵 ones_matrix = np.ones((2, 3)) ``` #### 基本属性 每种 Numpy 数组都有特定的属性来描述它的维度、大小和其他特征。 - **shape**: 表示数组的尺寸 (行数×列数)。 - **dtype**: 数据类型的说明符。 - **ndim**: 维度数量。 ```python array_example = np.array([[1, 2], [3, 4]]) print(array_example.shape) # 输出: (2, 2) print(array_example.dtype) # 输出: int64 print(array_example.ndim) # 输出: 2 ``` #### 数组拼接 对于多个 Numpy 数组之间的连接操作,可以利用 `np.concatenate` 函数实现按指定轴方向进行合并[^1][^4]。 ```python a = np.array([[1, 2], [3, 4]]) b = np.array([[5, 6]]) result_row_concat = np.concatenate((a, b), axis=0) # 按行拼接 result_col_concat = np.concatenate((a.T, b.T), axis=1).T # 转置后再按列拼接并转回原状 ``` #### 数组运算 支持逐元素算术运算以及广播机制下的复杂表达式求解[^3]。 ```python addition_result = a + result_row_concat[:len(a)] # 加法演示 multiplication_result = addition_result * array_example # 乘法规则应用 ``` #### 形状变换 调整现有数组结构而不改变实际存储顺序可通过 `.reshape()` 方法完成;而展平高阶张量到向量形式可调用`.flatten()`. ```python reshaped_array = ones_matrix.reshape(-1) # 将二维变一维 flattened_version = reshaped_array.flatten() ``` 以上就是有关于 Numpy 的一些基础知识及其实战技巧概览。希望这些内容能够帮助理解该工具包的强大之处!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值