有人知道如何在Python中从多维数组中提取列吗?
当前回答
>>> 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”和“重塑”来分配内存
示例:(用矩阵(3x4)的形状分配数组)
nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
其他回答
如果你有一个数组
a = [[1, 2], [2, 3], [3, 4]]
然后像这样提取第一列:
[row[0] for row in a]
结果是这样的:
[1, 2, 3]
如果你在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)
>>> 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])
>>> 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”和“重塑”来分配内存
示例:(用矩阵(3x4)的形状分配数组)
nrows = 3
ncols = 4
my_array = numpy.arange(nrows*ncols, dtype='double')
my_array = my_array.reshape(nrows, ncols)
你也可以用这个:
values = np.array([[1,2,3],[4,5,6]])
values[...,0] # first column
#[1,4]
注意:这对于内置数组和未对齐的数组无效(例如np.array([[1,2,3],[4,5,6,7]]))
推荐文章
- 把if-elif-else语句放在一行中?
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 如何修剪空白的数组值在php
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀