From ND to 1D arrays
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands
--
Chapters
00:00 From Nd To 1d Arrays
00:46 Accepted Answer Score 391
01:34 Answer 2 Score 31
01:47 Answer 3 Score 7
02:03 Answer 4 Score 3
02:27 Thank you
--
Full question
https://stackoverflow.com/questions/1373...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands
--
Chapters
00:00 From Nd To 1d Arrays
00:46 Accepted Answer Score 391
01:34 Answer 2 Score 31
01:47 Answer 3 Score 7
02:03 Answer 4 Score 3
02:27 Thank you
--
Full question
https://stackoverflow.com/questions/1373...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy
#avk47
ACCEPTED ANSWER
Score 391
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
In [12]: a = np.array([[1,2,3], [4,5,6]])
In [13]: b = a.ravel()
In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])
Note that ravel() returns a view of a when possible. So modifying b also modifies a. ravel() returns a view when the 1D elements are contiguous in memory, but would return a copy if, for example, a were made from slicing another array using a non-unit step size (e.g. a = x[::2]).
If you want a copy rather than a view, use
In [15]: c = a.flatten()
If you just want an iterator, use np.ndarray.flat:
In [20]: d = a.flat
In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>
In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]
ANSWER 2
Score 31
In [14]: b = np.reshape(a, (np.product(a.shape),))
In [15]: b
Out[15]: array([1, 2, 3, 4, 5, 6])
or, simply:
In [16]: a.flatten()
Out[16]: array([1, 2, 3, 4, 5, 6])
ANSWER 3
Score 7
For list of array with different size use following:
import numpy as np
# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]
# stack them
b = np.hstack(a)
print(b)
Output:
[1 2 3 4 5 6 7 8]
ANSWER 4
Score 3
One of the simplest way is to use flatten(), like this example :
import numpy as np
batch_y =train_output.iloc[sample, :]
batch_y = np.array(batch_y).flatten()
My array it was like this :
0
0 6
1 6
2 5
3 4
4 3
.
.
.
After using flatten():
array([6, 6, 5, ..., 5, 3, 6])
It's also the solution of errors of this type :
Cannot feed value of shape (100, 1) for Tensor 'input/Y:0', which has shape '(?,)'