Source From Here
Question
Say I have an array a:
I would like to convert it to a 1D array (i.e. a column vector) !
HowTo
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
Note that ravel() returns a view of a when possible. So modifying ary also modifies ex2. ]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. ary = x[::2]). If you want a copy rather than a view, use:
If you just want an iterator, use np.ndarray.flat:
Question
Say I have an array a:
- >>> import numpy as np
- >>> ary = np.array([[1,2,3],[4,5,6]])
- >>> ary
- array([[1, 2, 3],
- [4, 5, 6]])
HowTo
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
- >>> ex1 = ary.reshape(1, -1)
- >>> ex1
- array([[1, 2, 3, 4, 5, 6]])
- >>> ex1.shape
- (1, 6)
- >>> ex2 = ary.ravel()
- >>> ex2
- array([1, 2, 3, 4, 5, 6])
- >>> ex2.shape
- (6,)
- >>> ex3 = ary.flatten()
- >>> ex3
- array([1, 2, 3, 4, 5, 6])
- >>> ex3.shape
- (6,)
- >>> ary[0,0]=10
- >>> ary
- array([[10, 2, 3],
- [ 4, 5, 6]])
- >>> ex3
- array([1, 2, 3, 4, 5, 6])
- >>> ex4 = ary.flat
- >>> ex4
- <numpy.flatiter object at 0x2cbfce0>
- >>> list(ex4)
- [10, 2, 3, 4, 5, 6]
沒有留言:
張貼留言