Cannot Understand The Output Of This Code: Python List To 1-d Numpy Array
I tried to create turn a python list into a numpy array, but got very unintuitive output. Certainly I did something wrong, but out of curiosity I would like to know why I got such
Solution 1:
You created a five dimensional array.
a = [1, 5, 3, 6, 2]
b = np.ndarray(a)
print(b.shape)
gives
(1, 5, 3, 6, 2)
The first argument of the np.ndarray
is the shape of the array.
Your probably wanted
b = np.array(a)
print(b)
which gives
[1 5 3 6 2]
Solution 2:
You've created a n-dimensional array whereby n = 5 which is the length of the array passed (which form the dimensions as explained here).
It's likely you're looking for:
np.array(a)
Those numbers are float 0.
Solution 3:
To create an array from a list, use: b = np.array(a)
.
np.ndarray
is another numpy class, and the first argument of the function is the shape of the array (hence the shape of your array being b.shape -> (1, 5, 3, 6, 2)
)
Solution 4:
np.ndarray(shape, dtype=float....)
the argument require shape, so it will create a new array with shape (1, 5, 3, 6, 2) in your example
a = [1, 5, 3, 6, 2]
b = np.ndarray(a)
print(b.shape)
return
(1, 5, 3, 6, 2)
what you want is np.array
a = [1, 5, 3, 6, 2]
b = np.array(a)
print(b.shape)
return
(5,)
Post a Comment for "Cannot Understand The Output Of This Code: Python List To 1-d Numpy Array"