2

What I want to do is to turn a 2D array like this:

np.array([[ 0, 1, 2, 3], [ 1, 5, 6, 7]])

into this (a list with all numbers in):

[0,1,2,3,1,5,6,7]

is there any way to make it happen?

Nicole
  • 49
  • 1
  • 2
  • 2
    -1 https://www.google.co.in/search?q=flatten+a+2d+numpy+array – Ashwini Chaudhary Nov 13 '14 at 17:27
  • do you really want a list or just `np.flatten`?? – Padraic Cunningham Nov 13 '14 at 17:31
  • 2
    +1: googling "flatten" only works if you know to use the word "flatten", but if you know that, you already know the answer. – tom10 Nov 13 '14 at 17:34
  • Padraic Cunningham is right. You usually want to avoid lessening the nature of your datatypes. If you have a `numpy.array` to begin with, keep it as a `numpy.array`. Otherwise, it could cause errors/confusion when someone, thinking that it is still a `numpy.array`, tries to use it as one. –  Nov 13 '14 at 17:37

2 Answers2

3
x = np.array([[ 0, 1, 2, 3], [ 1, 5, 6, 7]])    

list(x.flat)    # if you want a list
#  [0, 1, 2, 3, 1, 5, 6, 7]

x.flatten()  # if you want a numpy array
#   array([0, 1, 2, 3, 1, 5, 6, 7])

It's unclear to me whether you want a list or numpy array, but they are both easy to get (although I assume you want a list since you tagged this question with list). It's reasonable to pick whichever you want or is most useful to you.

For many uses, numpy has significant advantages over lists, but there are also times that lists work better. For example, in many constructions, one gets items one at a time and doesn't know ahead of time the size of the resulting output array, and in this case it can make sense to build a list using append and then convert it to a numpy array to take an FFT.

There are other approaches to converting between lists and numpy arrays. When you have the need to do things to be different (eg, faster), be sure to look at the documentation or ask back here.

Community
  • 1
  • 1
tom10
  • 67,082
  • 10
  • 127
  • 137
0

Using 'raw' Python I was writing a simple player vs computer Tic Tac Toe game. The board was a 2D array of cells numbered 1 - 9. Player would select a cell to put their 'X' in. Computer would randomly select a cell to put their 'O' in from the remaining available cells. I wanted to transform the 2D board in a 1D list. Here's how.

>>> board=[["1","2","O"],["4","X","6"],["X","O","9"]]
>>> [ board[row][col] for row in range(len(board)) for col in range(len(board[row])) if board[row][col] != "X" if board[row][col] != "O" ]
['1', '2', '4', '6', '9']
>>> 
Clarius
  • 1,183
  • 10
  • 10