NBC
NBC

Reputation: 1698

split array based on delimiter

i have a numpy array like this:

 ['test_a','help_b','apple_c']

I want two arrays:

 ['test','help','apple']

and

 ['a','b','c']

Upvotes: 1

Views: 3577

Answers (5)

Udit Hari Vashisht
Udit Hari Vashisht

Reputation: 549

If it would have been a list. You can easily do it as under .

result1=[]
result2=[]
for item in input_list:
    r1, r2 = item.split('_')
    result1.append(r1)
    result2.append(r2)

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71580

OR:

>>> l=your_numpy_array.tolist()
>>> a,b=[i.split('_')[0] for i in l],[i.split('_')[1] for i in l]
>>> a
['test', 'help', 'apple']
>>> b
['a', 'b', 'c']
>>> 

Upvotes: 1

Lev Zakharov
Lev Zakharov

Reputation: 2427

Use list comprehension and tricky numpy rows unpacking:

a = np.array(['test_a','help_b','apple_c'])
x, y = np.array([x.split('_') for x in a]).T

Result:

x = array(['test', 'help', 'apple'], dtype='<U5')

y = array(['a', 'b', 'c'], dtype='<U5')

Upvotes: 1

chrisaycock
chrisaycock

Reputation: 37930

Given a list:

In [11]: xs = ['test_a','help_b','apple_c']

I can split each element and then "unzip" (transpose) the results:

In [12]: a, b = zip(*map(lambda x: x.split('_'), xs))

This is what I'm left with:

In [13]: a
Out[13]: ('test', 'help', 'apple')

In [14]: b
Out[14]: ('a', 'b', 'c')

Upvotes: 1

rafaelc
rafaelc

Reputation: 59274

Pure python solution:

x = np.array(['test_a','help_b','apple_c'])

a, b = zip(*[k.split('_') for k in x.tolist()])

>>> a # can always make this list(a)
('test', 'help', 'apple')

Using pandas

>>> pd.DataFrame(pd.Series(x).str.split('_').tolist())

    0       1
0   test    a
1   help    b
2   apple   c

such that

>>> df2[0].tolist()
['test', 'help', 'apple']

Upvotes: 2

Related Questions