将单个维度添加到NumPy向量的有效方法,以便切片分配起作用

时间:2012-03-01 03:32:38

标签: python numpy

在NumPy中,如何有效地将1-D对象制作成2-D对象,其中单个维度是从当前对象推断出来的(即列表应该是1xlength或lengthx1向量)?

 # This comes from some other, unchangeable code that reads data files.
 my_list = [1,2,3,4]

 # What I want to do:
 my_numpy_array[some_index,:] = numpy.asarray(my_list)

 # The above doesn't work because of a broadcast error, so:
 my_numpy_array[some_index,:] = numpy.reshape(numpy.asarray(my_list),(1,len(my_list)))

 # How to do the above without the call to reshape?
 # Is there a way to directly convert a list, or vector, that doesn't have a
 # second dimension, into a 1 by length "array" (but really it's still a vector)?

5 个答案:

答案 0 :(得分:41)

在最常见的情况下,向数组添加额外维度的最简单方法是在该位置建立索引时使用关键字None来添加额外维度。例如

my_array = numpy.array([1,2,3,4])

my_array[None, :] # shape 1x4

my_array[:, None] # shape 4x1

答案 1 :(得分:4)

为什么不简单地添加方括号?

>> my_list
[1, 2, 3, 4]
>>> numpy.asarray([my_list])
array([[1, 2, 3, 4]])
>>> numpy.asarray([my_list]).shape
(1, 4)

..等等,第二个想法,为什么你的切片分配失败了?它不应该:

>>> my_list = [1,2,3,4]
>>> d = numpy.ones((3,4))
>>> d
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
>>> d[0,:] = my_list
>>> d[1,:] = numpy.asarray(my_list)
>>> d[2,:] = numpy.asarray([my_list])
>>> d
array([[ 1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.],
       [ 1.,  2.,  3.,  4.]])

甚至:

>>> d[1,:] = (3*numpy.asarray(my_list)).T
>>> d
array([[  1.,   2.,   3.,   4.],
       [  3.,   6.,   9.,  12.],
       [  1.,   2.,   3.,   4.]])

答案 2 :(得分:3)

expand_dims怎么办?

np.expand_dims(np.array([1,2,3,4]), 0)

具有(1,4)形状,而

np.expand_dims(np.array([1,2,3,4]), 1)

的形状为(4,1)

答案 3 :(得分:2)

import numpy as np
a = np.random.random(10)
sel = np.at_least2d(a)[idx]

答案 4 :(得分:1)

您始终可以使用dstack()复制数组:

import numpy

my_list = array([1,2,3,4])
my_list_2D = numpy.dstack((my_list,my_list));