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
  • 7,174
  • 2
  • 8
  • 23
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)
Schnick
  • 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,213
  • 2
  • 10
  • 19
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
  • 1,017
  • 9
  • 19
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
  • 98
  • 1
  • 7
0

You can try:

np.asarray([ val for arr in p for val in arr[:-1]])
Rachit Tayal
  • 1,190
  • 14
  • 20