0

I am wondering if there is an easy way to 'append' new elements to an array, but not at the end

Imagine I have a vector

a = np.array([1,2,3,4,5,6])

I want to append a new vector

b = np.array([1,1,1,1]) 

to a, starting from element 3 so that the new array would be

c = np.array([1,2,3,5,6,7,1]) 

that is the last 3 elements of array a are resulting from a+b while the new element just belong to C

Any ideas?

THX

I tried just append!

3
  • "that is the last 3 elements of array a are resulting from a+b while the new element just belong to C" What you are describing isn't really an "append" operation. Commented Nov 7, 2022 at 19:48
  • I tried to change the question to make it more clear. Commented Nov 7, 2022 at 19:53
  • 1
    @user Please clarify the logic behind what you're trying to do. What's the connection between the arrays you start with ([1,2,3,4,5,6] and [1,1,1,1]) and the array you end up with [1,2,3,5,6,7,1]? My best guess at the logic here is that you want to find [1,2,3,4+1,5+1,6+1,0+1]. Is that right? Commented Nov 7, 2022 at 19:54

1 Answer 1

2

Using numpy with pad:

a = np.array([1,2,3,4,5,6])
b = np.array([1,1,1,1])
# or
# a = [1,2,3,4,5,6]
# b = [1,1,1,1]

n = 3
extra = len(b)-len(a)+n

c = np.pad(a, (0, extra))
c[n:] += b

Output:

array([1, 2, 3, 5, 6, 7, 1])
Sign up to request clarification or add additional context in comments.

1 Comment

OP has since clarified that the question is indeed about numpy arrays

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.