f. c.
f. c.

Reputation: 1135

How to remove brackets from a python array?

I have an array like this:

>>>Opt
array([[array([[0.5]])]], dtype=object)

How to remove these brackets and get the value of 0.5 as a single floating point?

I have tried

>>>np.array(Opt)
array([[array([[0.5]])]], dtype=object)
>>>Opt.ravel()
array([[array([[0.5]])]], dtype=object)
>>>Opt.flatten()
array([[array([[0.5]])]], dtype=object)

None of these works. Is it because of the data type "object"?

Upvotes: 1

Views: 179

Answers (2)

f. c.
f. c.

Reputation: 1135

I find out the best way to do it is using item().

Opt.item().item()

Upvotes: 0

m.rp
m.rp

Reputation: 748

That is a 4-dimensional numpy array you defined, so in this instance to basic way to get the number you have to navigate the four dimensions:

import numpy as np

the_array = np.array([[np.array([[0.5]])]], dtype=object)
print(the_array[0][0][0][0])

Output:

0.5

I don't know what you want to do with this array, based on your use case there may be better approaches to your problem.

dtype=object means that you defined an array of pointers to Python objects, this defines both the way memory is managed when allocating space for the array and the permitted operations on the elements.

Upvotes: 1

Related Questions