Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 980
bioslime Avatar asked Jul 31 '12 12:07

bioslime


People also ask

How do you make a 2D array into 1D?

Every row in your 2D array is placed end to end in your 1D array. i gives which row you are in, and j gives the column (how far into that row). so if you are in the ith row, you need to place i complete rows end to end, then append j more onto that to get your single array index.

How do you make a NumPy 1D array?

Python Numpy – Create One Dimensional Array One dimensional array contains elements only in one dimension. In other words, the shape of the numpy array should contain only one value in the tuple. To create a one dimensional array in Numpy, you can use either of the array(), arange() or linspace() numpy functions.


1 Answers

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, :]
like image 90
khstacking Avatar answered Sep 21 '22 17:09

khstacking