I have one problem. How can I convert:
import numpy as npa = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])
To:
b = np.array([[0.1,0.2,0.3], [0.3,0.4,0.5], [0.5,0.6,0.7]])
I have one problem. How can I convert:
import numpy as npa = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])
To:
b = np.array([[0.1,0.2,0.3], [0.3,0.4,0.5], [0.5,0.6,0.7]])
import numpy as np
a = np.array([['0.1 0.2 0.3'], ['0.3 0.4 0.5'], ['0.5 0.6 0.7']])# Create a placeholder list
b = []for element in a:# use a list comprehension to# * take the zeroeth element in each row of the 'a' array and# split the string on spaces# * parse through each substring thus produced# * convert each of those substrings into floats# * store it in the list called temp.temp = [float(num) for num in element[0].split()]# Add each temp list to the parent list 'b'b.append(temp)# Convert b into an np.array
b = np.array(b)
This looks like this:
b = []for element in a:temp = [float(num) for num in element[0].split(' ')]b.append(temp)
b = np.array(b)
array([[0.1, 0.2, 0.3],[0.3, 0.4, 0.5],[0.5, 0.6, 0.7]])
I tend to like this as an approach since it uses the native casting abilities of numpy. I have not tested it, but I would not be surprised if that produces a speedup in the conversion process for large arrays.
# transform 'a' to an array of rows full of individual strings
# use the .astype() method to then cast each value as a float
a = np.array([row[0].split() for row in a])
b = a.astype(np.float)
Hattip to @ahmed_yousif