Numpy索引切片不丢失维度信息 [英] Numpy index slice without losing dimension information

查看:35
本文介绍了Numpy索引切片不丢失维度信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 numpy 并希望在不丢失维度信息的情况下索引一行.

I'm using numpy and want to index a row without losing the dimension information.

import numpy as np
X = np.zeros((100,10))
X.shape        # >> (100, 10)
xslice = X[10,:]
xslice.shape   # >> (10,)  

在这个例子中,xslice 现在是一维,但我希望它是 (1,10).在 R 中,我会使用 X[10,:,drop=F].numpy.js 中有类似的东西吗?我在文档中找不到它,也没有看到类似的问题.

In this example xslice is now 1 dimension, but I want it to be (1,10). In R, I would use X[10,:,drop=F]. Is there something similar in numpy. I couldn't find it in the documentation and didn't see a similar question asked.

谢谢!

推荐答案

x[None, 10, :] 或等效(但更易读)x[np.newaxis, 10, :].

It's probably easiest to do x[None, 10, :] or equivalently (but more readable) x[np.newaxis, 10, :].

至于为什么它不是默认设置,就我个人而言,我发现不断拥有具有单一维度的数组会很快变得烦人.我猜麻木的开发者也有同样的感觉.

As far as why it's not the default, personally, I find that constantly having arrays with singleton dimensions gets annoying very quickly. I'd guess the numpy devs felt the same way.

此外,numpy 可以很好地处理广播数组,因此通常没有理由保留切片来自的数组的维度.如果你这样做了,那么事情就像:

Also, numpy handle broadcasting arrays very well, so there's usually little reason to retain the dimension of the array the slice came from. If you did, then things like:

a = np.zeros((100,100,10))
b = np.zeros(100,10)
a[0,:,:] = b

要么不起作用,要么实施起来更加困难.

either wouldn't work or would be much more difficult to implement.

(或者至少这是我对 numpy 开发者在切片时删除维度信息背后的推理的猜测)

(Or at least that's my guess at the numpy dev's reasoning behind dropping dimension info when slicing)

这篇关于Numpy索引切片不丢失维度信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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