13

I'm trying to plot a histogram with matplotlib. I need to convert my one-line 2D Array

[[1,2,3,4]] # shape is (1,4)

into a 1D Array

[1,2,3,4] # shape is (4,)

How can I do this?

5 Answers 5

18

Adding ravel as another alternative for future searchers. From the docs,

It is equivalent to reshape(-1, order=order).

Since the array is 1xN, all of the following are equivalent:

  • arr1d = np.ravel(arr2d)
  • arr1d = arr2d.ravel()
  • arr1d = arr2d.flatten()
  • arr1d = np.reshape(arr2d, -1)
  • arr1d = arr2d.reshape(-1)
  • arr1d = arr2d[0, :]
Sign up to request clarification or add additional context in comments.

Comments

12

You can directly index the column:

>>> import numpy as np
>>> x2 = np.array([[1,2,3,4]])
>>> x2.shape
(1, 4)
>>> x1 = x2[0,:]
>>> x1
array([1, 2, 3, 4])
>>> x1.shape
(4,)

Or you can use squeeze:

>>> xs = np.squeeze(x2)
>>> xs
array([1, 2, 3, 4])
>>> xs.shape
(4,)

Comments

2

reshape will do the trick.

There's also a more specific function, flatten, that appears to do exactly what you want.

1 Comment

More specifically, arr.reshape(-1) converts an array to 1D. But the equivalent ravel() is better, as it is meant specifically to indicate a conversion to 1D.
2

the answer provided by mtrw does the trick for an array that actually only has one line like this one, however if you have a 2d array, with values in two dimension you can convert it as follows

a = np.array([[1,2,3],[4,5,6]])

From here you can find the shape of the array with np.shape and find the product of that with np.product this now results in the number of elements. If you now use np.reshape() to reshape the array to one length of the total number of element you will have a solution that always works.

np.reshape(a, np.product(a.shape))
>>> array([1, 2, 3, 4, 5, 6])

Comments

1

Use numpy.flat

import numpy as np
import matplotlib.pyplot as plt

a = np.array([[1,0,0,1],
              [2,0,1,0]])

plt.hist(a.flat, [0,1,2,3])

Histogram of Flattened Array

The flat property returns a 1D iterator over your 2D array. This method generalizes to any number of rows (or dimensions). For large arrays it can be much more efficient than making a flattened copy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.