In Matlab, one can access a column of an array with :
:
在Matlab中,可以使用::访问数组的列
>> array=[1 2 3; 4 5 6]
array =
1 2 3
4 5 6
>> array(:,2)
ans =
2
5
How to do this in Python?
如何在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>
Addendum
I'd like an example applied to an array of dimensions greater than three:
我想要一个应用于大于3的维度数组的示例:
>> 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
7 个解决方案
#1
12
Use Numpy.
使用Numpy。
>>> import numpy as np
>>>
>>> a = np.array([[1,2,3],[4,5,6]])
>>> a[:, 2]
array([3, 6])
If you come from Matlab, this should be of interest: http://www.scipy.org/NumPy_for_Matlab_Users
如果你来自Matlab,这应该是有意义的:http://www.scipy.org/NumPy_for_Matlab_Users
#2
8
You can group data in a two-dimensional list by column using the built-in zip()
function:
您可以使用内置的zip()函数按列对二维列表中的数据进行分组:
>>> array=[[1,2,3],[4,5,6]]
>>> zip(*array)
[(1, 4), (2, 5), (3, 6)]
>>> zip(*array)[1]
(2, 5)
Note that the index starts at 0, so to get the second column as in your example you use zip(*array)[1]
instead of zip(*array)[2]
. zip()
returns tuples instead of lists, depending on how you are using it this may not be a problem, but if you need lists you can always do map(list, zip(*array))
or list(zip(*array)[1])
to do the conversion.
请注意,索引从0开始,因此要获得第二列,如示例所示,使用zip(* array)[1]而不是zip(* array)[2]。 zip()返回元组而不是列表,这取决于你如何使用它可能不是问题,但如果你需要列表,你可以随时做map(list,zip(* array))或list(zip(* array) [1])进行转换。
#3
4
If you use Matlab, you probably will want to install NumPy: Using NumPy, you can do this:
如果您使用Matlab,您可能需要安装NumPy:使用NumPy,您可以这样做:
In [172]: import numpy as np
In [173]: arr = np.matrix('1 2 3; 4 5 6')
In [174]: arr
Out[174]:
matrix([[1, 2, 3],
[4, 5, 6]])
In [175]: arr[:,2]
Out[175]:
matrix([[3],
[6]])
Since Python uses 0-based indexing (while Matlab uses 1-based indexing), to get the same slice you posted you would do:
由于Python使用基于0的索引(而Matlab使用基于1的索引),要获得您发布的相同切片,您将执行以下操作:
In [176]: arr[:,1]
Out[176]:
matrix([[2],
[5]])
It is easy to build numpy arrays of higher dimension as well. You could use np.dstack
for instance:
很容易构建更高维度的numpy数组。你可以使用np.dstack作为例子:
In [199]: B = np.dstack( (np.eye(3), np.ones((3,3)), np.arange(9).reshape(3,3)) )
In [200]: B.shape
Out[200]: (3, 3, 3)
In [201]: B[:,:,0]
Out[201]:
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
In [202]: B[:,:,1]
Out[202]:
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
In [203]: B[:,:,2]
Out[203]:
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
And here is the array formed from the second column from each of the 3 arrays above:
这里是从上面3个数组中的每个数组的第二列形成的数组:
In [204]: B[:,1,:]
Out[204]:
array([[ 0., 1., 1.],
[ 1., 1., 4.],
[ 0., 1., 7.]])
Numpy doesn't have a function to create magic squares, however. sniff
然而,Numpy没有创建魔术方块的功能。吸气
#4
2
Indexing / slicing with Python using the colon results in things a bit differently than matlab. If you have your array, [:]
will copy it. If you want all values at a specific index of nested arrays, you probably want something like this:
使用冒号使用Python进行索引/切片会导致与matlab略有不同。如果您有阵列,[:]将复制它。如果您希望嵌套数组的特定索引处的所有值,您可能需要以下内容:
array = [[1,2,3],[4,5,6]]
col1 = [inner[0] for inner in array] # note column1 is index 0 in Python.
#5
1
If using nested lists, you can use a list comprehension:
如果使用嵌套列表,则可以使用列表推导:
array = [ [1, 2, 3], [4, 5, 6] ]
col2 = [ row[1] for row in array ]
Keep in mind that since Python doesn't natively know about matrices, col2
is a list, and as such both "rows" and "columns" are the same type, namely lists. Use the numpy
package for better support for matrix math.
请记住,由于Python本身并不了解矩阵,因此col2是一个列表,因此“行”和“列”都是相同的类型,即列表。使用numpy包可以更好地支持矩阵数学。
#6
0
def get_column(array, col):
result = []
for row in array:
result.appen(row[col])
return result
Use like this (remember that indexes start from 0):
像这样使用(记住索引从0开始):
>>> a = [[1,2,3], [2,3,4]]
>>> get_column(a, 1)
[2, 3]
#7
0
Use a list comprehension to build a list of values from that column:
使用列表推导来构建该列的值列表:
def nthcolumn(n, matrix):
return [row[n] for row in matrix]
Optionally use itemgetter
if you need a (probably slight) performance boost:
如果您需要(可能是轻微的)性能提升,可以选择使用itemgetter:
from operator import itemgetter
def nthcolumn(n, matrix):
nthvalue = itemgetter(n)
return [nthvalue(row) for row in matrix]
#1
12
Use Numpy.
使用Numpy。
>>> import numpy as np
>>>
>>> a = np.array([[1,2,3],[4,5,6]])
>>> a[:, 2]
array([3, 6])
If you come from Matlab, this should be of interest: http://www.scipy.org/NumPy_for_Matlab_Users
如果你来自Matlab,这应该是有意义的:http://www.scipy.org/NumPy_for_Matlab_Users
#2
8
You can group data in a two-dimensional list by column using the built-in zip()
function:
您可以使用内置的zip()函数按列对二维列表中的数据进行分组:
>>> array=[[1,2,3],[4,5,6]]
>>> zip(*array)
[(1, 4), (2, 5), (3, 6)]
>>> zip(*array)[1]
(2, 5)
Note that the index starts at 0, so to get the second column as in your example you use zip(*array)[1]
instead of zip(*array)[2]
. zip()
returns tuples instead of lists, depending on how you are using it this may not be a problem, but if you need lists you can always do map(list, zip(*array))
or list(zip(*array)[1])
to do the conversion.
请注意,索引从0开始,因此要获得第二列,如示例所示,使用zip(* array)[1]而不是zip(* array)[2]。 zip()返回元组而不是列表,这取决于你如何使用它可能不是问题,但如果你需要列表,你可以随时做map(list,zip(* array))或list(zip(* array) [1])进行转换。
#3
4
If you use Matlab, you probably will want to install NumPy: Using NumPy, you can do this:
如果您使用Matlab,您可能需要安装NumPy:使用NumPy,您可以这样做:
In [172]: import numpy as np
In [173]: arr = np.matrix('1 2 3; 4 5 6')
In [174]: arr
Out[174]:
matrix([[1, 2, 3],
[4, 5, 6]])
In [175]: arr[:,2]
Out[175]:
matrix([[3],
[6]])
Since Python uses 0-based indexing (while Matlab uses 1-based indexing), to get the same slice you posted you would do:
由于Python使用基于0的索引(而Matlab使用基于1的索引),要获得您发布的相同切片,您将执行以下操作:
In [176]: arr[:,1]
Out[176]:
matrix([[2],
[5]])
It is easy to build numpy arrays of higher dimension as well. You could use np.dstack
for instance:
很容易构建更高维度的numpy数组。你可以使用np.dstack作为例子:
In [199]: B = np.dstack( (np.eye(3), np.ones((3,3)), np.arange(9).reshape(3,3)) )
In [200]: B.shape
Out[200]: (3, 3, 3)
In [201]: B[:,:,0]
Out[201]:
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
In [202]: B[:,:,1]
Out[202]:
array([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
In [203]: B[:,:,2]
Out[203]:
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
And here is the array formed from the second column from each of the 3 arrays above:
这里是从上面3个数组中的每个数组的第二列形成的数组:
In [204]: B[:,1,:]
Out[204]:
array([[ 0., 1., 1.],
[ 1., 1., 4.],
[ 0., 1., 7.]])
Numpy doesn't have a function to create magic squares, however. sniff
然而,Numpy没有创建魔术方块的功能。吸气
#4
2
Indexing / slicing with Python using the colon results in things a bit differently than matlab. If you have your array, [:]
will copy it. If you want all values at a specific index of nested arrays, you probably want something like this:
使用冒号使用Python进行索引/切片会导致与matlab略有不同。如果您有阵列,[:]将复制它。如果您希望嵌套数组的特定索引处的所有值,您可能需要以下内容:
array = [[1,2,3],[4,5,6]]
col1 = [inner[0] for inner in array] # note column1 is index 0 in Python.
#5
1
If using nested lists, you can use a list comprehension:
如果使用嵌套列表,则可以使用列表推导:
array = [ [1, 2, 3], [4, 5, 6] ]
col2 = [ row[1] for row in array ]
Keep in mind that since Python doesn't natively know about matrices, col2
is a list, and as such both "rows" and "columns" are the same type, namely lists. Use the numpy
package for better support for matrix math.
请记住,由于Python本身并不了解矩阵,因此col2是一个列表,因此“行”和“列”都是相同的类型,即列表。使用numpy包可以更好地支持矩阵数学。
#6
0
def get_column(array, col):
result = []
for row in array:
result.appen(row[col])
return result
Use like this (remember that indexes start from 0):
像这样使用(记住索引从0开始):
>>> a = [[1,2,3], [2,3,4]]
>>> get_column(a, 1)
[2, 3]
#7
0
Use a list comprehension to build a list of values from that column:
使用列表推导来构建该列的值列表:
def nthcolumn(n, matrix):
return [row[n] for row in matrix]
Optionally use itemgetter
if you need a (probably slight) performance boost:
如果您需要(可能是轻微的)性能提升,可以选择使用itemgetter:
from operator import itemgetter
def nthcolumn(n, matrix):
nthvalue = itemgetter(n)
return [nthvalue(row) for row in matrix]