这是在一行代码中为numpy数组添加额外维度的最佳方法吗? [英] Is this the best way to add an extra dimension to a numpy array in one line of code?

查看:41
本文介绍了这是在一行代码中为numpy数组添加额外维度的最佳方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果k是任意形状的numpy数组,那么k.shape = (s1, s2, s3, ..., sn),并且我想对其进行整形以使k.shape变为(s1, s2, ..., sn, 1),这是在一行中完成它的最佳方法吗?

If k is an numpy array of an arbitrary shape, so k.shape = (s1, s2, s3, ..., sn), and I want to reshape it so that k.shape becomes (s1, s2, ..., sn, 1), is this the best way to do it in one line?

k.reshape(*(list(k.shape) + [1])

推荐答案

像这样更容易:

k.reshape(k.shape + (1,))

但是,如果您只想在末尾添加一个空尺寸,则应使用numpy.newaxis:

But if all you want is to add an empty dimension at the end, you should use numpy.newaxis:

import numpy as np
k = k[..., np.newaxis]

k = k[..., None]

(请参见切片文档).

这篇关于这是在一行代码中为numpy数组添加额外维度的最佳方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆