0

I have a list containing 1D numpy arrays different sizes. Now I want to remove the last value of each numpy array inside this list and concatenate them into one 1D numpy array.

As an example, I have this:

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

and I would like to have that:

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

I will appreciate any help to approach this issue.

1
  • This similar question might help you. Commented Jul 28, 2021 at 17:34

6 Answers 6

1

You can try:

np.hstack([a[:-1] for a in p])
Sign up to request clarification or add additional context in comments.

Comments

0

I would recommend you to create a new list from the arrays and use this list to initialize a new numpy array, like this:

new_list = []
for i in range(len(p)):
    new_list += p[i].tolist()[:-1]
p = np.array(new_list)

Comments

0
c=[]
for i in p:
    a=i[:-1]
    for j in a:  c.append(j)`
p=numpy.array(c)

this is how i would do it with a normal list item. But i'm not 100% sure how numpy.array functions, it may be the same. - although some brief testing showed it was the same.

Comments

0

Here is the solution

import numpy as np
p=[np.array([1,2,3,4,5,6]),np.array([1,2,3]),np.array([1,2])]
final = []
for i in p:
    for k in range(len(i)-1):
        final.append(i[k])

Comments

0

A one-liner using list comprehension (I think you could do this with an iterator directly to numpy too) would be:

p = np.concatenate( [arr[:-1] for arr in p])

Comments

0

You can try:

np.asarray([ val for arr in p for val in arr[:-1]])

Comments

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.