1

Let's say we have two arrays

a = [1, 2]

b = [ [A, B, C], [D, E, F] ]

I want to make c = [ [1,A, B, C], [2, D, E, F] ] by combing a & b

How to achieve that?

The amounts of 1st level children are the same in both a and b.

2 Answers 2

2

You need to reshape a so it becomes a 2x1 array then you can use hstack to horizontally stack the arrays:

In[13]:
np.hstack([a.reshape((2,1)), b])

Out[13]: 
array([['1', 'A', 'B', 'C'],
       ['2', 'D', 'E', 'F']], 
      dtype='<U11')

As suggested by numpy master @Divakar, if you slice the array and pass None as one of the axes, you can introduce or reshape the array without the need to reshape:

In[14]:
np.hstack([a[:,None], b])

Out[14]: 
array([['1', 'A', 'B', 'C'],
       ['2', 'D', 'E', 'F']], 
      dtype='<U11')

It's explained in the docs, look for newaxis example

Sign up to request clarification or add additional context in comments.

3 Comments

To make it generic : a[:,None].
or a.reshape(-1, 1) if you feel reshape is clearer
@DanielF I generally prefer explicit code so it's clearer IMO, depends on how well seasoned you are with numpy to know what passing -1 will do
0

You could use zip and a list comprehension:

a = [1, 2]
b = [['a', 'b', 'c'], ['d', 'e', 'f']]
c = [[e] + l for e, l in zip(a, b)]
print(c) #=> [[1, 'a', 'b', 'c'], [2, 'd', 'e', 'f']]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.