分离多维数组numpy python

时间:2012-03-25 08:37:31

标签: python numpy

我有一个像下面这样的numpy数组

[[ 1 2 3 4 ]
 [ 5 6 7 8 ] 

......... ]

所以基本上我想创建4个(可以是不同的)列表

 list_1 = [1,5...], list_2 = [2,6....] and so on.

这样做的pythonic方式是什么?

3 个答案:

答案 0 :(得分:2)

给定一个numpy数组

>>> numpy.array([[x for x in xrange(i,i+5)] for i in xrange(0,100,10)])
array([[ 0,  1,  2,  3,  4],
       [10, 11, 12, 13, 14],
       [20, 21, 22, 23, 24],
       [30, 31, 32, 33, 34],
       [40, 41, 42, 43, 44],
       [50, 51, 52, 53, 54],
       [60, 61, 62, 63, 64],
       [70, 71, 72, 73, 74],
       [80, 81, 82, 83, 84],
       [90, 91, 92, 93, 94]])

首先必须transpose

>>> narray=numpy.array([[x for x in xrange(i,i+5)] for i in xrange(0,100,10)])
>>> tarray=numpy.transpose(narray)
array([[ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90],
       [ 1, 11, 21, 31, 41, 51, 61, 71, 81, 91],
       [ 2, 12, 22, 32, 42, 52, 62, 72, 82, 92],
       [ 3, 13, 23, 33, 43, 53, 63, 73, 83, 93],
       [ 4, 14, 24, 34, 44, 54, 64, 74, 84, 94]])

然后转换为list

>>> larray=tarray.tolist()
>>> larray
[[0, 10, 20, 30, 40, 50, 60, 70, 80, 90], [1, 11, 21, 31, 41, 51, 61, 71, 81, 91], [2, 12, 22, 32, 42, 52, 62, 72, 82, 92], [3, 13, 23, 33, 43, 53, 63, 73, 83, 93], [4, 14, 24, 34, 44, 54, 64, 74, 84, 94]]

现在您可以将larray编入索引larray[0], larray[1]以获取各个列表。

答案 1 :(得分:2)

鉴于此

>>> a  = array([[1,2,3,4], [5,6,7,8], [9, 10,11,12]])
>>> a
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

您可以使用slicing

>>> list1 = a[:,0]
>>> list1
array([1, 5, 9])
>>> list1 = a[:,1]
>>> list1
array([ 2,  6, 10])

答案 2 :(得分:1)

a=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
list1=[]
list2=[]
list3=[]
list4=[]
for x in a:
    for i,y in enumerate(x):
        if i==0:
            list1.append(y)
        elif i==1:
            list2.append(y)
        elif i==2:
            list3.append(y)
        elif i==3:
            list4.append(y)


>>> print(list1)
[1, 5, 9, 13]

>>> print(list2)
[2, 6, 10, 14]

>>> print(list3)
[3, 7, 11, 15]

>>> print(list4)
[4, 8, 12, 16]

动态:

>>>a=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
>>>list=[[] for _ in range(len(a))]
>>>for x in a:
    for i,y in enumerate(x):
      list[i].append(y)
>>>print(list)
[[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]]