如何访问 NumPy 多维数组的第 i 列? [英] How to access the ith column of a NumPy multidimensional array?

查看:26
本文介绍了如何访问 NumPy 多维数组的第 i 列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

test = numpy.array([[1, 2], [3, 4], [5, 6]])

test[i] 获取数组的 ith<​​/em> 行(例如 [1, 2]).如何访问 ith<​​/em> 列?(例如 [1, 3, 5]).此外,这会是一项昂贵的操作吗?

解决方案

>>>测试[:,0]数组([1, 3, 5])

同样,

<预><代码>>>>测试 [1,:]数组([3, 4])

让您访问行.这在 NumPy 参考的第 1.4 节(索引)中有介绍.这很快,至少根据我的经验.这肯定比访问循环中的每个元素要快得多.

Suppose I have:

test = numpy.array([[1, 2], [3, 4], [5, 6]])

test[i] gets me ith line of the array (eg [1, 2]). How can I access the ith column? (eg [1, 3, 5]). Also, would this be an expensive operation?

解决方案

>>> test[:,0]
array([1, 3, 5])

Similarly,

>>> test[1,:]
array([3, 4])

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

这篇关于如何访问 NumPy 多维数组的第 i 列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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