ryabchenko-a
ryabchenko-a

Reputation: 85

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 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

Upvotes: 0

Views: 252

Answers (4)

Ian
Ian

Reputation: 109

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

Upvotes: 0

Mark Bakker
Mark Bakker

Reputation: 821

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]

Upvotes: 2

Youyoun
Youyoun

Reputation: 338

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

Upvotes: 1

Rambatino
Rambatino

Reputation: 4914

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.

Upvotes: 1

Related Questions