insert comma into this array so as to call each element individually

Question:

I have the following array to which I am trying to insert a comma between the numbers so that I can call each element individually, ie a[0]=-4.5e-2, a[1]=7.8e-3 etc

a = np.array(['-4.5e-2 7.8e-3 1e-2'])

Output

array([['-4.5e-2 7.8e-3 1e-2'],
       dtype='<U19')

Desired output

array([-4.5e-2, 7.8e-3, 1e-2])
Asked By: user9106985

||

Answers:

You can convert into dtype float64,

In [1]: np.array(['-4.5e-2 7.8e-3 1e-2'.split()]).astype('float64')
Out[1]: array([[-0.045 ,  0.0078,  0.01  ]])

Values are:

In [2]: -4.5e-2
Out[2]: -0.045

In [3]: 7.8e-3
Out[3]: 0.0078

In [4]: 1e-2
Out[4]: 0.01

If you want to represent it exact the same way you need to keep it as a Unicode string or string. Like this,

In [5]: np.array(['-4.5e-2 7.8e-3 1e-2'.split()])
Out[5]: array([['-4.5e-2', '7.8e-3', '1e-2']], dtype='<U7')

If the array has more values you can do this,

In [1]: value = np.array([['1.28353e-02 3.24985e-02 6.12448e-02'], ['3.62696e-01 4.77613e-01 5.70936e-01 ']], dtype=object)
    
In [2]: np.array([i[0].split() for i in value]).astype('float64')
Out[2]: 
array([[-0.045 ,  0.0078,  0.01  ],
       [-0.045 ,  0.0078,  0.01  ]])
Answered By: Rahul K P
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.