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.

  • This similar [question](https://stackoverflow.com/questions/32932866/numpy-the-best-way-to-remove-the-last-element-from-1-dimensional-array) might help you. – Joaquim Procopio Jul 28 '21 at 17:34

6 Answers6

1

You can try:

np.hstack([a[:-1] for a in p])
bb1
  • 5,933
  • 2
  • 6
  • 22
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)
YN1CK
  • 51
  • 3
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.

Robert Cotterman
  • 2,115
  • 2
  • 7
  • 16
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])
Lakshika Parihar
  • 729
  • 6
  • 16
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])
econbernardo
  • 83
  • 1
  • 6
0

You can try:

np.asarray([ val for arr in p for val in arr[:-1]])
Rachit Tayal
  • 1,040
  • 13
  • 17