Cannot understand the output of this code: python list to 1-d numpy array

我怕爱的太早我们不能终老 提交于 2020-07-10 10:27:38

问题


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 an output. Here is my code:

import numpy as np

# Exercise 2
a = [1, 5, 3, 6, 2]
b = np.ndarray(a)
print(b, b.dtype)

the output was

[[[[[0.00000000e+000 6.93284651e-310]
    [6.93284792e-310 6.93284744e-310]
    [6.93284744e-310 6.93284744e-310]
    [6.93284744e-310 6.93284744e-310]
    [6.93284744e-310 6.93284744e-310]
    [6.93284744e-310 6.93284744e-310]]

   [[6.93284744e-310 2.20882835e-314]
    [6.93284743e-310 6.93284743e-310]
    [6.93284743e-310 6.93284650e-310]
    [6.93284744e-310 6.93284744e-310]
    [6.93284744e-310 6.93284744e-310]
    [6.93284744e-310 6.93284744e-310]]

   ... (12 more blocks similar to ones above)

   [[6.93284871e-310 6.93284871e-310]
    [6.93284745e-310 6.93284871e-310]
    [6.93284651e-310 6.93284871e-310]
    [6.93284745e-310 6.93284871e-310]
    [6.93284871e-310 6.93284745e-310]
    [6.93284727e-310 6.93284871e-310]]]]] float64

回答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]



回答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.




回答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))




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


来源:https://stackoverflow.com/questions/62661651/cannot-understand-the-output-of-this-code-python-list-to-1-d-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!