Skip to content Skip to sidebar Skip to footer

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'], [

Solution 1:

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.]])

Solution 2:

Iterate through rows and use split(',') to split each row at the commas, and put the result in a new numpy array with a numeric data type:

import numpy as np

a = np.array([['1,2,3'], ['3,4,5']])
b = np.array([x[0].split(',') for x in a], dtype=np.float32)
print(b)

#[[ 1.  2.  3.]
# [ 3.  4.  5.]]                                          

Solution 3:

I would like to propose this if you don't mind having them as a vector

np.array([["asa,asd"], ["dasd,asdaf,asfasf"]], dtype=object)
Out[31]: 
array([['asa,asd'],
      ['dasd,asdaf,asfasf']], dtype=object)
np.concatenate(np.char.split(Out[31].astype(str), ",").ravel())
Out[32]: array(['asa', 'asd', 'dasd', 'asdaf', 'asfasf'], dtype='<U6')

Post a Comment for "Split 2D NumPy Array Of Strings On "," Character"