Klyment
Klyment

Reputation: 187

How to insert value to a 2 dimensions array from a 1 dimension array using Numpy

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.

Upvotes: 1

Views: 51

Answers (2)

EdChum
EdChum

Reputation: 393933

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

Upvotes: 2

Danil Speransky
Danil Speransky

Reputation: 30453

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

Upvotes: 0

Related Questions