# Flatten a 2d numpy array into 1d array in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

A 2d numpy array is an array of arrays. In this article we will see how to flatten it to get the elements as one dimensional arrays.

## With flatten

The flatten function in numpy is a direct way to convert the 2d array in to a 1D array.

## Example

Live Demo

import numpy as np
array2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]])
# printing initial arrays
print("Given array:\n",array2D)
# Using flatten()
res = array2D.flatten()
# Result
print("Flattened array:\n ", res)

## Output

Running the above code gives us the following result −

Given array:
[[31 12 43]
[21 9 16]
[ 0 9 0]]
Flattened array:
[31 12 43 21 9 16 0 9 0]

## With ravel

There is another function called ravel which will do a similar thing of flattening the 2D array into 1D.

## Example

Live Demo

import numpy as np
array2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]])
# printing initial arrays
print("Given array:\n",array2D)
# Using ravel
res = array2D.ravel()
# Result
print("Flattened array:\n ", res)

## Output

Running the above code gives us the following result −

Given array:
[[31 12 43]
[21 9 16]
[ 0 9 0]]
Flattened array:
[31 12 43 21 9 16 0 9 0]