Home > Back-end >  converting a numpy string array to numpy float array
converting a numpy string array to numpy float array

Time:06-11

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!

CodePudding user response:

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)}
  • Related