python - 在 Python 中访问数组列的最佳方法是什么?

标签 python arrays

在 Matlab 中,可以使用 : 访问数组的列:

>> array=[1 2 3; 4 5 6]

array =

     1     2     3
     4     5     6


>> array(:,2)

ans =

     2
     5

如何在 Python 中执行此操作?

>>> array=[[1,2,3],[4,5,6]]
>>> array[:,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>> array[:][2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

附录

我想要一个应用于维度大于三的数组的示例:

>> B = cat(3, eye(3), ones(3), magic(3))

B(:,:,1) =

     1     0     0
     0     1     0
     0     0     1


B(:,:,2) =

     1     1     1
     1     1     1
     1     1     1


B(:,:,3) =

     8     1     6
     3     5     7
     4     9     2

>> B(:,:,1)                             

ans =

     1     0     0
     0     1     0
     0     0     1

>> B(:,2,:)

ans(:,:,1) =

     0
     1
     0


ans(:,:,2) =

     1
     1
     1


ans(:,:,3) =

     1
     5
     9

最佳答案

使用Numpy .

>>> import numpy as np
>>> 
>>> a = np.array([[1,2,3],[4,5,6]])
>>> a[:, 2]
array([3, 6])

如果您来自 Matlab,这应该会引起您的兴趣:Link

关于python - 在 Python 中访问数组列的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8900288/

相关文章:

python - 对数据框中的行子集进行连接和求和

python - 使用 Python 从 Google 文档中删除资源

javascript - 使用索引从已排序的多 3 元素数组中删除重复项

c++ - 将数据文件读取到数组,传递给成员函数 - 丢失

python - 使用 rpy2 导入并使用 R 'heavy' 包

python - 播放音频文件后 pygame 没有响应

Python使用子字符串在字符串中查找字符串

c++ - 为什么不能将数组的地址分配给指针?

java - byte[] 到 String 和 String 到 byte[]

c++ - 如何定义自定义比较函数以根据一维数组排序对矩阵进行排序