Home > Mobile >  How to get an element of a NumPy list without bracket and ''
How to get an element of a NumPy list without bracket and ''

Time:10-29

I have a NumPy list (Distances). When I print it, the result is:

array([[  1.        ],
       [600.        ],
       [456.03971033],
       [294.94188261],
       [286.47232436],
       [ 92.08606785]])

However, I want to get any specific element of this list as a float number without any brackets, array, and '' sign. Note that I don't want to print it, I need to have the number in another variable like this:

element1 = Distance[0]

Result is: array([1.])

But I want it to be just: 1.

CodePudding user response:

You can first flatten the array to make it one dimensional:

flatdistance = Distance.flatten()
element1 = flatdistance[0]

CodePudding user response:

This is a 2-D array, so you need to specify both indices:

element1 = Distance[0][0]

And the 600. will be at 1,0:

element2 = Distance[1][0]

CodePudding user response:

Note that your result is a matrix, (a list of lists in python). So when you are doing Distance[0] you are correctly accessing the first element, that is a list. It has two dimensions. So if you want to have that value you can do:

Distance[0][0].

However, if your lists have always one element, try flat it with

flat_distance = Distance[:, -1]

And then flat_distance[0] is equal to 1.

  • Related