user_12
user_12

Reputation: 2129

How to join multiple rows sequentially in a numpy array?

I've a data like this,

data = [array(['a', 'b', 'c']), 
        array([['d', 'e', 'f'], ['g', 'h', 'i']]), 
        array([['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r']])]

I want to join values in inner list sequentially. This is the desired output that I need.

[['a', 'b', 'c'], ['d g', 'e h', 'f i'], ['j m p', 'k n q', 'l o r']]

I tried using using multiple loops and join but it's not giving me required output.

for i in data:
    for j in i:
        print(" ".join(j))

I'm not really sure on how to achieve this? Need an efficient and faster approach because my original data is really large.

Upvotes: 1

Views: 228

Answers (3)

Andy L.
Andy L.

Reputation: 25239

Since you say there are also timestamp values, I cast to string for every sub-array.

out = [[' '.join(tup) for tup in zip(*arr.astype(str))] if arr.ndim > 1 else arr.tolist() 
               for arr in data]

Out[89]: [['a', 'b', 'c'], ['d g', 'e h', 'f i'], ['j m p', 'k n q', 'l o r']]

Upvotes: 1

hpaulj
hpaulj

Reputation: 231395

In [300]: [np.array([' '.join(ij) for ij in zip(*np.atleast_2d(row))]) for row in data]        
Out[300]: 
[array(['a', 'b', 'c'], dtype='<U1'),
 array(['d g', 'e h', 'f i'], dtype='<U3'),
 array(['j m p', 'k n q', 'l o r'], dtype='<U5')]

The first array is 1d, thus requiring the atleast_2d for consistency. Most the rest is just iterative application of string join.

Upvotes: 3

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

Try:

res=list(map(lambda x: list(map(' '.join, zip(*x))) if isinstance(x[0], list) else x, data))

Outputs:

[['a', 'b', 'c'], ['d g', 'e h', 'f i'], ['j m p', 'k n q', 'l o r']]

Upvotes: 2

Related Questions