np.newaxis

本文详细介绍了如何使用NumPy的np.newaxis进行数组维度的扩展,包括从一维到二维,甚至更高维度的转换方法。通过具体代码示例,展示了np.newaxis在不同场景下的应用,帮助读者理解和掌握NumPy数组操作的高级技巧。
  x1 = np.array([1, 2, 3, 4, 5])
    # the shape of x1 is (5,)
    x1_new = x1[:, np.newaxis]
    # now, the shape of x1_new is (5, 1)
    # array([[1],
    #        [2],
    #        [3],
    #        [4],
    #        [5]])
    x1_new = x1[np.newaxis,:]	
	# now, the shape of x1_new is (1, 5)
   # array([[1, 2, 3, 4, 5]])

再来一个例子

    In [124]: arr = np.arange(5*5).reshape(5,5)
    
    In [125]: arr.shape
    Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)
np.newaxisNumPy 中用于增加数组维度的关键字,其作用是为数组插入一个新的维度,从而改变数组的形状(shape),增加的维度大小为 1。np.newaxis等价于None,可以作为索引使用,用于在指定位置增加一个维度[^1]。 ### 基本使用方法 #### 在第 0 维增加一个维度 ```python import numpy as np arr = np.array([1, 2, 3]) # 原始数组 shape: (3,) new_arr = arr[np.newaxis, :] # shape: (1, 3) print(new_arr) # Output: # [[1 2 3]] ``` #### 在最后一维增加一个维度 ```python import numpy as np arr = np.array([1, 2, 3]) new_arr = arr[..., np.newaxis] print(new_arr.shape) # Output: (3, 1) ``` #### 在指定位置增加一个维度 ```python import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) new_arr = arr[:, np.newaxis, :] print(new_arr.shape) # Output: (2, 1, 3) ``` ### 替换用法 np.newaxis可以替换成None,二者具有一样的效果,只是np.newaxis可读性更强。对于连续的多个":",有更简便的表达方式"..."。例如: ```python import numpy as np a = np.array([1, 2, 3]) b = a[..., None, :] # 等同于 b = a[..., np.newaxis, :] print(b.shape) # Output: (1, 3) ``` ### 更多维度增加示例 - 一维数组变二维数组,在第 0 维增加维度 ```python import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = x[np.newaxis, :] print(y.shape) # Output: (1, 10) ``` - 一维数组变二维数组,在最后一维增加维度 ```python import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = x[:, np.newaxis] print(y.shape) # Output: (10, 1) ``` - 一维数组变三维数组 ```python import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) y = x[np.newaxis, :, np.newaxis] print(y.shape) # Output: (1, 10, 1) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值