-2

I want to reshape a list into an numpy array of a specific dimension. My list looks like the following:

my_list = [array([[1],
                  [2],
                  [3],
                  [4]],
                 [[2],
                  [3],
                  [4],
                  [1]],
                 [[3],
                  [4],
                  [2],
                  [1]])]

I want to convert this list into a numpy array and reshape it to a dimension of (3, 4), such as the following:

my_list = [array([1, 2, 3, 4],
                 [2, 3, 4, 1],       
                 [3, 4, 1, 2])]

I have checked some earlier threads on this, such as Transposing a NumPy array and SciPy documentation, but can't seem to understand how it works and could not convert my list to what my desired array form.

ayhan
  • 70,170
  • 20
  • 182
  • 203
Chris T.
  • 1,699
  • 7
  • 23
  • 45
  • You can't `reshape` a list; you can reshape an array inside a list. In this case the distinction between list and array is important. – hpaulj Jun 11 '17 at 19:00
  • Thanks for enlightening me on this, I will check out the documentation and rethink about my question in this post. – Chris T. Jun 11 '17 at 19:11

2 Answers2

3
>>> a
[array([[[1],
        [2],
        [3],
        [4]],

       [[2],
        [3],
        [4],
        [1]],

       [[3],
        [4],
        [2],
        [1]]])]
>>> a[0].shape
(3, 4, 1)
>>> a[0] = a[0].reshape(3,4)
>>> a
[array([[1, 2, 3, 4],
       [2, 3, 4, 1],
       [3, 4, 2, 1]])]
>>> a[0].shape
(3, 4)
>>> 
wwii
  • 23,232
  • 7
  • 37
  • 77
  • Thanks, this is what I am trying to get at. My "list" comes with an "array" inside the square brackets (which I don't know why), and it seems to have prevented my from reshaping my list into desired format. Don't really understand why someone so vehemently voted down this post... – Chris T. Jun 11 '17 at 18:47
  • @ChrisT. - usually no vehemence involved, just someone's opinion of the quality of the question. – wwii Jun 11 '17 at 18:55
1

You don't need the array in the inner most call, np.asarray will happily take a nested python list and convert the whole thing to an ndarray, then you just call .reshape to make into the shape you want.

my_list = [[[1],
            [2],
            [3],
            [4]],
           [[2],
            [3],
            [4],
            [1]],
           [[3],
            [4],
            [2],
            [1]]]
np.asarray(my_list).reshape(3,4)
Matti Lyra
  • 12,828
  • 8
  • 49
  • 67