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

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

问题描述

如果 k 是一个任意形状的 numpy 数组,那么 k.shape = (s1, s2, s3, ..., sn),我想重塑它以便 k.shape 变成了 (s1, s2, ..., sn, 1),这是最好的一行代码吗?

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

解决方案

这样更容易:

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

但如果你只想在最后添加一个空维度,你应该使用 numpy.newaxis:

将 numpy 导入为 npk = k[..., np.newaxis]

k = k[..., None]

(请参阅关于切片的文档)..>

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])

解决方案

It's easier like this:

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

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]

or

k = k[..., None]

(See the documentation on slicing).

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

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