bioslime
bioslime

Reputation: 1961

Turn 2D NumPy array into 1D array for plotting a histogram

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?

Upvotes: 13

Views: 28103

Answers (5)

user3569257
user3569257

Reputation: 115

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])

Upvotes: 2

khstacking
khstacking

Reputation: 637

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, :]

Upvotes: 18

Waylon Flinn
Waylon Flinn

Reputation: 20257

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.

Upvotes: 1

mtrw
mtrw

Reputation: 35088

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,)

Upvotes: 12

Kos
Kos

Reputation: 72241

reshape will do the trick.

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

Upvotes: 2

Related Questions