Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

python - Split 2D NumPy array of strings on "," character

I have a 2D NumPy of strings array like: a = array([['1,2,3'], ['3,4,5']], dtype=object) and I would like to convert it into a 2D Numpy array like this: a = array([['1','2','3'], ['4','5','6']]). I would then like to also convert the strings to floats, so the final array would look like this: a = array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]). Any help is greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since it's an object array, we might as well iterate and use plain python split:

In [118]: a = np.array([['1,2,3'], ['3,4,5']], dtype=object)
In [119]: a.shape
Out[119]: (2, 1)
In [120]: np.array([x.split(',') for x in a.ravel()])
Out[120]: 
array([['1', '2', '3'],
       ['3', '4', '5']], dtype='<U1')
In [122]: np.array([x.split(',') for x in a.ravel()],dtype=float)
Out[122]: 
array([[1., 2., 3.],
       [3., 4., 5.]])

I raveled it to simplify iteration. Plus the result doesn't need that 2nd size 1 dimension.

There is a np.char function that applies split to elements of an array, but the result is messier:

In [129]: a.astype(str)
Out[129]: 
array([['1,2,3'],
       ['3,4,5']], dtype='<U5')
In [130]: np.char.split(_, sep=',')
Out[130]: 
array([[list(['1', '2', '3'])],
       [list(['3', '4', '5'])]], dtype=object)
In [138]: np.stack(Out[130].ravel()).astype(float)
Out[138]: 
array([[1., 2., 3.],
       [3., 4., 5.]])

Another way:

In [132]: f = np.frompyfunc(lambda astr: np.array(astr.split(','),float),1,1)
In [133]: f(a)
Out[133]: 
array([[array([1., 2., 3.])],
       [array([3., 4., 5.])]], dtype=object)
In [136]: np.stack(_.ravel())
Out[136]: 
array([[1., 2., 3.],
       [3., 4., 5.]])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...