converting a numpy string array to numpy float array

Issue

I’m reading a csv file to dict. I want the key to be string, and the value to be an array of a float, like this:

"A":array[5.19494526e-02  1.17357977e-01  5.19494526e-02]

but I’m getting this:

"A":array['5.19494526e-02  1.17357977e-01  5.19494526e-02'].

trying to run this code to fix it:

a=pd.read_csv('Encoded.csv', header=None, index_col=0, squeeze=True).to_dict()
encoded={}
for key, value in a.items():
    x = np.array(value)
    y = np.asarray(x, dtype=np.float32)
    encoded[key]=y
print(encoded)
return encoded

but I’m getting "could not convert string to float", why?
Thanks!

Solution

I think the issue is that in the line y = np.asarray(x, dtype=np.float32), the variable x is an array of length one containing multiple space-separated substrings that can each be converted to a float. However, the string itself cannot be converted to float.

You can try replacing that line with this:

y = np.asarray(x[0].split(), dtype=np.float32)

Input

{'A': array(['5.19494526e-02  1.17357977e-01  5.19494526e-02'], dtype='<U46')}

Output

{'A': array([0.05194945, 0.11735798, 0.05194945], dtype=float32)}

Answered By – constantstranger

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published