问题:如何从多维数组中提取列?
有人知道如何在Python中从多维数组中提取列吗?
Does anybody know how to extract a column from a multi-dimensional array in Python?
回答 0
>>> import numpy as np
>>> A = np.array([[1,2,3,4],[5,6,7,8]])
>>> A
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> A[:,2] # returns the third columm
array([3, 7])
另请参阅:“ numpy.arange”和“ reshape”以分配内存
示例:(使用矩阵整形(3×4)分配数组)
nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
>>> import numpy as np
>>> A = np.array([[1,2,3,4],[5,6,7,8]])
>>> A
array([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> A[:,2] # returns the third columm
array([3, 7])
See also: “numpy.arange” and “reshape” to allocate memory
Example: (Allocating a array with shaping of matrix (3×4))
nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
回答 1
可能是您正在使用NumPy数组吗?Python具有数组模块,但是不支持多维数组。普通的Python列表也是一维的。
但是,如果您有一个简单的二维列表,例如:
A = [[1,2,3,4],
[5,6,7,8]]
然后您可以提取一个像这样的列:
def column(matrix, i):
return [row[i] for row in matrix]
提取第二列(索引1):
>>> column(A, 1)
[2, 6]
或者,简单地:
>>> [row[1] for row in A]
[2, 6]
Could it be that you’re using a NumPy array? Python has the array module, but that does not support multi-dimensional arrays. Normal Python lists are single-dimensional too.
However, if you have a simple two-dimensional list like this:
A = [[1,2,3,4],
[5,6,7,8]]
then you can extract a column like this:
def column(matrix, i):
return [row[i] for row in matrix]
Extracting the second column (index 1):
>>> column(A, 1)
[2, 6]
Or alternatively, simply:
>>> [row[1] for row in A]
[2, 6]
回答 2
如果你有一个像
a = [[1, 2], [2, 3], [3, 4]]
然后像这样提取第一列:
[row[0] for row in a]
所以结果看起来像这样:
[1, 2, 3]
If you have an array like
a = [[1, 2], [2, 3], [3, 4]]
Then you extract the first column like that:
[row[0] for row in a]
So the result looks like this:
[1, 2, 3]
回答 3
看看这个!
a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
它与上面相同,只是它使zip工作更整洁,但需要单个数组作为参数,* a语法将多维数组解压缩为单个数组参数
check it out!
a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
it is the same thing as above except somehow it is neater the zip does the work but requires single arrays as arguments, the *a syntax unpacks the multidimensional array into single array arguments
回答 4
def get_col(arr, col):
return map(lambda x : x[col], arr)
a = [[1,2,3,4], [5,6,7,8], [9,10,11,12],[13,14,15,16]]
print get_col(a, 3)
Python中的map函数是另一种方法。
def get_col(arr, col):
return map(lambda x : x[col], arr)
a = [[1,2,3,4], [5,6,7,8], [9,10,11,12],[13,14,15,16]]
print get_col(a, 3)
map function in Python is another way to go.
回答 5
>>> x = arange(20).reshape(4,5)
>>> x array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
如果您想使用第二栏,可以使用
>>> x[:, 1]
array([ 1, 6, 11, 16])
>>> x = arange(20).reshape(4,5)
>>> x array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
if you want the second column you can use
>>> x[:, 1]
array([ 1, 6, 11, 16])
回答 6
[matrix[i][column] for i in range(len(matrix))]
[matrix[i][column] for i in range(len(matrix))]
回答 7
如果您喜欢map-reduce样式的python,而不是列表推导,itemgetter运算符也可以提供帮助!
# tested in 2.4
from operator import itemgetter
def column(matrix,i):
f = itemgetter(i)
return map(f,matrix)
M = [range(x,x+5) for x in range(10)]
assert column(M,1) == range(1,11)
The itemgetter operator can help too, if you like map-reduce style python, rather than list comprehensions, for a little variety!
# tested in 2.4
from operator import itemgetter
def column(matrix,i):
f = itemgetter(i)
return map(f,matrix)
M = [range(x,x+5) for x in range(10)]
assert column(M,1) == range(1,11)
回答 8
您也可以使用此:
values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]
注意:这不适用于内置数组且未对齐(例如np.array([[1,2,3],[4,5,6,7]]))
You can use this as well:
values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]
Note: This is not working for built-in array and not aligned (e.g. np.array([[1,2,3],[4,5,6,7]]) )
回答 9
我想您想从数组(例如下面的数组)中提取列
import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
现在,如果要获取格式的第三列
D=array[[3],
[7],
[11]]
然后,您需要首先使数组成为矩阵
B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)
现在,您可以像在excel中一样进行元素明智的计算。
I think you want to extract a column from an array such as an array below
import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
Now if you want to get the third column in the format
D=array[[3],
[7],
[11]]
Then you need to first make the array a matrix
B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)
And now you can do element wise calculations much like you would do in excel.
回答 10
假设我们有n X m
矩阵(n
行和m
列)说5行和4列
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]]
要提取python中的列,我们可以像这样使用列表理解
[ [row[i] for row in matrix] for in range(4) ]
您可以将矩阵中的列数替换为4。结果是
[ [1,5,9,13,17],[2,10,14,18],[3,7,11,15,19],[4,8,12,16,20] ]
let’s say we have n X m
matrix(n
rows and m
columns) say 5 rows and 4 columns
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]]
To extract the columns in python, we can use list comprehension like this
[ [row[i] for row in matrix] for in range(4) ]
You can replace 4 by whatever number of columns your matrix has. The result is
[ [1,5,9,13,17],[2,10,14,18],[3,7,11,15,19],[4,8,12,16,20] ]
回答 11
array = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
col1 = [val[1] for val in array]
col2 = [val[2] for val in array]
col3 = [val[3] for val in array]
col4 = [val[4] for val in array]
print(col1)
print(col2)
print(col3)
print(col4)
Output:
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
array = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
col1 = [val[1] for val in array]
col2 = [val[2] for val in array]
col3 = [val[3] for val in array]
col4 = [val[4] for val in array]
print(col1)
print(col2)
print(col3)
print(col4)
Output:
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
回答 12
使用矩阵的另一种方法
>>> from numpy import matrix
>>> a = [ [1,2,3],[4,5,6],[7,8,9] ]
>>> matrix(a).transpose()[1].getA()[0]
array([2, 5, 8])
>>> matrix(a).transpose()[0].getA()[0]
array([1, 4, 7])
One more way using matrices
>>> from numpy import matrix
>>> a = [ [1,2,3],[4,5,6],[7,8,9] ]
>>> matrix(a).transpose()[1].getA()[0]
array([2, 5, 8])
>>> matrix(a).transpose()[0].getA()[0]
array([1, 4, 7])
回答 13
如果您在Python中有一个二维数组(不是numpy),则可以像这样提取所有列,
data = [
['a', 1, 2],
['b', 3, 4],
['c', 5, 6]
]
columns = list(zip(*data))
print("column[0] = {}".format(columns[0]))
print("column[1] = {}".format(columns[1]))
print("column[2] = {}".format(columns[2]))
执行此代码会产生
>>> print("column[0] = {}".format(columns[0]))
column[0] = ('a', 'b', 'c')
>>> print("column[1] = {}".format(columns[1]))
column[1] = (1, 3, 5)
>>> print("column[2] = {}".format(columns[2]))
column[2] = (2, 4, 6)
当然,您可以按索引提取单个列(例如columns[0]
)
If you have a two-dimensional array in Python (not numpy), you can extract all the columns like so,
data = [
['a', 1, 2],
['b', 3, 4],
['c', 5, 6]
]
columns = list(zip(*data))
print("column[0] = {}".format(columns[0]))
print("column[1] = {}".format(columns[1]))
print("column[2] = {}".format(columns[2]))
Executing this code will yield,
>>> print("column[0] = {}".format(columns[0]))
column[0] = ('a', 'b', 'c')
>>> print("column[1] = {}".format(columns[1]))
column[1] = (1, 3, 5)
>>> print("column[2] = {}".format(columns[2]))
column[2] = (2, 4, 6)
Of course, you can extract a single column by index (e.g. columns[0]
)
回答 14
尽管使用zip(*iterable)
了转置嵌套列表,但是如果嵌套列表的长度不同,也可以使用以下内容:
map(None, *[(1,2,3,), (4,5,), (6,)])
结果是:
[(1, 4, 6), (2, 5, None), (3, None, None)]
因此,第一列是:
map(None, *[(1,2,3,), (4,5,), (6,)])[0]
#>(1, 4, 6)
Despite using zip(*iterable)
to transpose a nested list, you can also use the following if the nested lists vary in length:
map(None, *[(1,2,3,), (4,5,), (6,)])
results in:
[(1, 4, 6), (2, 5, None), (3, None, None)]
The first column is thus:
map(None, *[(1,2,3,), (4,5,), (6,)])[0]
#>(1, 4, 6)
回答 15
好吧,有点晚…
如果性能很重要并且您的数据呈矩形,则也可以将其存储为一维,并通过常规切片访问列,例如…
A = [[1,2,3,4],[5,6,7,8]] #< assume this 4x2-matrix
B = reduce( operator.add, A ) #< get it one-dimensional
def column1d( matrix, dimX, colIdx ):
return matrix[colIdx::dimX]
def row1d( matrix, dimX, rowIdx ):
return matrix[rowIdx:rowIdx+dimX]
>>> column1d( B, 4, 1 )
[2, 6]
>>> row1d( B, 4, 1 )
[2, 3, 4, 5]
整洁的是,这真的很快。但是,负索引在这里不起作用!因此,您无法按索引-1访问最后一列或最后一行。
如果需要负索引,可以稍微调整访问器功能,例如
def column1d( matrix, dimX, colIdx ):
return matrix[colIdx % dimX::dimX]
def row1d( matrix, dimX, dimY, rowIdx ):
rowIdx = (rowIdx % dimY) * dimX
return matrix[rowIdx:rowIdx+dimX]
Well a ‘bit’ late …
In case performance matters and your data is shaped rectangular, you might also store it in one dimension and access the columns by regular slicing e.g. …
A = [[1,2,3,4],[5,6,7,8]] #< assume this 4x2-matrix
B = reduce( operator.add, A ) #< get it one-dimensional
def column1d( matrix, dimX, colIdx ):
return matrix[colIdx::dimX]
def row1d( matrix, dimX, rowIdx ):
return matrix[rowIdx:rowIdx+dimX]
>>> column1d( B, 4, 1 )
[2, 6]
>>> row1d( B, 4, 1 )
[2, 3, 4, 5]
The neat thing is this is really fast. However, negative indexes don’t work here! So you can’t access the last column or row by index -1.
If you need negative indexing you can tune the accessor-functions a bit, e.g.
def column1d( matrix, dimX, colIdx ):
return matrix[colIdx % dimX::dimX]
def row1d( matrix, dimX, dimY, rowIdx ):
rowIdx = (rowIdx % dimY) * dimX
return matrix[rowIdx:rowIdx+dimX]
回答 16
如果要获取不止一列,请使用slice:
a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(a[:, [1, 2]])
[[2 3]
[5 6]
[8 9]]
If you want to grab more than just one column just use slice:
a = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print(a[:, [1, 2]])
[[2 3]
[5 6]
[8 9]]
回答 17
我更喜欢下一条提示:将矩阵命名为matrix_a
use column_number
,例如:
import numpy as np
matrix_a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
column_number=2
# you can get the row from transposed matrix - it will be a column:
col=matrix_a.transpose()[column_number]
I prefer the next hint:
having the matrix named matrix_a
and use column_number
, for example:
import numpy as np
matrix_a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
column_number=2
# you can get the row from transposed matrix - it will be a column:
col=matrix_a.transpose()[column_number]
回答 18
只需使用transpose(),然后您就可以像获得行一样轻松获得列
matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColum]
Just use transpose(), then you can get the colummns as easy as you get rows
matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColum]
回答 19
矩阵中的所有列到新列表中:
N = len(matrix)
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]
All columns from a matrix into a new list:
N = len(matrix)
column_list = [ [matrix[row][column] for row in range(N)] for column in range(N) ]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。