np.newaxis终极解释

功能:np.newaxis是用来给数组a增加维度的
格式:a[np.newaxis:的组合],如a[:,np.newaxis]a[np.newaxis, np.newaxis, :]
详解:np.newaxis[]中第几位,a.shape的第几维就变成1,a的原来的维度依次往后排。
例子:若a.shape=(a ,b, c)
a[:, np.newaxis].shape= (a, 1, b, c)
a[:, np.newaxis, np.newaxis].shape= (a, 1, 1, b, c)
a[np.newaxis, :].shape= (1, a, b, c)
a[np.newaxis, np.newaxis, :].shape= (1, 1, a, b, c)
a[np.newaxis, :, np.newaxis].shape= (1, a, 1, b, c)
a[np.newaxis, :, np.newaxis, :].shape= (1, a, 1, b, c)
这么多例子应该看明白了吧。。
实例代码
另外,np.newaxis=None,看代码最后一行

import numpy as np

x = np.arange(24).reshape(2, 3, 4)

# print('x:\n', x)
print('x.shape=', x.shape)

# print('x[:, np.newaxis]:\n', x[:, np.newaxis])
print('x[:, np.newaxis].shape=', x[:, np.newaxis].shape)

# print('x[:, np.newaxis, np.newaxis]:\n', x[:, np.newaxis, np.newaxis])
print('x[:, np.newaxis, np.newaxis].shape=', x[:, np.newaxis, np.newaxis].shape)


# print('x:\n', x)
print('x.shape=', x.shape)

# print('x[np.newaxis, :]:\n', x[np.newaxis, :])
print('x[np.newaxis, :].shape=', x[np.newaxis, :].shape)

# print('x[np.newaxis, np.newaxis, :]:\n', x[np.newaxis, np.newaxis, :])
print('x[np.newaxis, np.newaxis, :].shape=', x[np.newaxis, np.newaxis, :].shape)

# print('x[np.newaxis, :, np.newaxis]:\n', x[np.newaxis, :, np.newaxis])
print('x[np.newaxis, :, np.newaxis].shape=', x[np.newaxis, :, np.newaxis].shape)

# print('x[np.newaxis, :, np.newaxis, :]:\n', x[None, :, None, :])
print('x[np.newaxis, :, np.newaxis, :].shape=', x[None, :, None, :].shape)  # 另外,np.newaxis=None
x.shape= (2, 3, 4)
x[:, np.newaxis].shape= (2, 1, 3, 4)
x[:, np.newaxis, np.newaxis].shape= (2, 1, 1, 3, 4)
x.shape= (2, 3, 4)
x[np.newaxis, :].shape= (1, 2, 3, 4)
x[np.newaxis, np.newaxis, :].shape= (1, 1, 2, 3, 4)
x[np.newaxis, :, np.newaxis].shape= (1, 2, 1, 3, 4)
x[np.newaxis, :, np.newaxis, :].shape= (1, 2, 1, 3, 4)
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值