Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

Let’s say I have two NumPy arrays, a and b:

a = np.array([

    [1, 2, 3],

    [2, 3, 4]

    ])

b = np.array([8,9])

And I would like to append the same array b to every row (ie. adding multiple columns) to get an array, c:

b = np.array([

    [1, 2, 3, 8, 9],

    [2, 3, 4, 8, 9]

    ])

How can I do this easily and efficiently in NumPy?

I am especially concerned about its behaviour with big datasets (where a is much bigger than b), is there any way around creating many copies (ie. a.shape[0]) of b?

Related to  this question, but with multiple values.

1 Answer

0 votes
by (41.4k points)

Here, you can make a recipient array and then copy the values to it:

a = np.arange(300).reshape(100,3)

b=np.array([8,9])

res = np.zeros((100,5),int)

res[:,:3]=a

res[:,3:]=b

If you wish to learn about NumPy visit this NumPy Tutorial.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
4 answers
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...