(python numpy) np.array.shape 中 (3,)、(3,1)、(1,3)的区别

(python numpy) np.array.shape 中 (3,)、(3,1)、(1,3)的区别

被人问到这个问题,就记录一下吧

1. (3,)

(3,)是 [ x , y , z ] [x,y,z] [x,y,z]的形式,即为一维数组,访问数组元素用一个index
for example:

>>> array1 = np.array([1,2,3])
>>> array1.shape
(3,)
2. (3,1)

(3,1)是 [ [ x ] , [ y ] , [ z ] ] [[x],[y],[z]] [[x],[y],[z]]的形式,即为二维数组,含有三行,每行一个元素,访问数组元素用两个index
for example:

>>> array2 = np.array([[1],[2],[3]])
>>> array2.shape
(3, 1)
3. (3,)

(1,3)是 [ [ x , y , z ] ] [[x,y,z]] [[x,y,z]]的形式,即为一维数组,含有一行,每行三个元素,访问数组元素用一个index
for example:

>>> array3 = np.array([[1,2,3]])
>>> array3.shape
(1, 3)
### Python 中 `numpy.array` 的使用方法 #### 创建数组 可以利用多种方式来创建 NumPy 数组。最常见的方式是从列表或其他序列类型的对象转换而来。 ```python import numpy as np # 从列表创建一维数组 data_list = [1, 2, 3, 4] array_from_list = np.array(data_list) print(array_from_list) # 输出: [1 2 3 4] # 从嵌套列表创建多维数组 nested_lists = [[1, 2], [3, 4]] multi_dim_array = np.array(nested_lists) print(multi_dim_array) # 输出: # [[1 2] # [3 4]] ``` #### 数据类型指定 当调用 `np.array()` 函数时,可以通过设置 dtype 参数来自定义数据类型[^3]。 ```python custom_dtype_array = np.array([1, 2, 3, 4], dtype=float) print(custom_dtype_array) # 输出: [1. 2. 3. 4.] ``` #### 基本操作 NumPy 提供了一系列用于处理数组的方法和支持向量化运算的功能。 ##### 形状变换 改变现有数组形状而不修改其内容: ```python original_shape = np.arange(8).reshape((2, 4)) reshaped = original_shape.reshape(-1, 2) print(f"Original shape:\n{original_shape}") print(f"\nReshaped to (-1, 2):\n{reshaped}") ``` ##### 数学计算 执行逐元素加减乘除等算术运算以及广播机制下的矩阵运算。 ```python vector_a = np.array([1, 2]) vector_b = np.array([3, 4]) addition_result = vector_a + vector_b multiplication_result = vector_a * vector_b print(addition_result) # 输出: [4 6] print(multiplication_result) # 输出: [3 8] ``` #### 类型转换 可以在 NumPy 数组与 Python 列表间互相转换。 ```python py_list = [9, 8, 7, 6] converted_to_np_array = np.array(py_list) back_to_py_list = converted_to_np_array.tolist() print(converted_to_np_array) # 输出: [9 8 7 6] print(back_to_py_list) # 输出: [9, 8, 7, 6] ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值