如何从多维数组中提取列?

发布于 2024-07-21 23:17:54 字数 31 浏览 4 评论 0原文

有谁知道如何在Python中从多维数组中提取列?

Does anybody know how to extract a column from a multi-dimensional array in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

吝吻 2024-07-28 23:17:55

如果你在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)

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)
尝蛊 2024-07-28 23:17:55
>>> 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])
香草可樂 2024-07-28 23:17:55

一探究竟!

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

明天过后 2024-07-28 23:17:55
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.

云巢 2024-07-28 23:17:55
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]
栀子花开つ 2024-07-28 23:17:55
[matrix[i][column] for i in range(len(matrix))]
[matrix[i][column] for i in range(len(matrix))]
总攻大人 2024-07-28 23:17:55

如果您喜欢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)
蒗幽 2024-07-28 23:17:55

您也可以使用它:

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]]) )

ヅ她的身影、若隐若现 2024-07-28 23:17:55

假设我们有 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] ]

給妳壹絲溫柔 2024-07-28 23:17:55

我认为您想从数组中提取一列,例如下面的数组

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.

つ低調成傷 2024-07-28 23:17:55

使用矩阵的另一种方法

>>> 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])
冬天旳寂寞 2024-07-28 23:17:55

只需使用 transpose(),即可像获取行一样轻松获取列

matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColumns]

Just use transpose(), then you can get the columns as easy as you get rows

matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColumns]
千秋岁 2024-07-28 23:17:55

如果您想获取不止一列,只需使用切片:

 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]]
爱冒险 2024-07-28 23:17:55

好吧,有点晚了……

如果性能很重要并且您的数据是矩形的,您也可以将其存储在一维中并通过常规切片访问列,例如……

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]
注定孤独终老 2024-07-28 23:17:55

尽管使用 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)
苏佲洛 2024-07-28 23:17:55

我更喜欢下一个提示:
具有名为 matrix_a 的矩阵并使用 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]
甜`诱少女 2024-07-28 23:17:55

矩阵中的所有列都放入新列表中:

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) ]
沧桑㈠ 2024-07-28 23:17:54

难道您正在使用 NumPy 数组? Python 有 array 模块,但不支持多维数组。 普通的 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]
逆蝶 2024-07-28 23:17:54

如果您有一个像这样的数组

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]
十年九夏 2024-07-28 23:17:54
>>> 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”来分配内存

示例:(通过矩阵形状 (3x4) 分配数组)

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 (3x4))

nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文