Python Forum
How to remove some elements from an array in python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to remove some elements from an array in python?
#8
I would have used numpy and np.where + np.delete (it has been fully detailled here after to see how it works); actually only lines 9-11-12-(22) are necessary.

import numpy as np

# a list is created first using numpy
N = 5_000
M = np.random.randint(-2, 10_000, size=(N)).tolist()

# it starts here
MaxNumber = 4_000
Mat = np.asarray(M)

Ind = np.where(Mat >= MaxNumber)
n = np.shape(Ind)[1]
print(f"There's {n} elements to remove")

Mat = np.delete(Mat, np.s_[Ind])

# you can of course sort the array if it's needed
Indexes = Mat.argsort()
MatSorted = Mat[Indexes]

# now you can go back to a list
M_new = MatSorted.tolist()
Reply


Messages In This Thread
RE: How to remove some elements from an array in python? - by paul18fr - Nov-28-2023, 07:48 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 1,806 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 8,561 May-17-2022, 11:38 AM
Last Post: Larz60+
  Replace elements of array with elements from another array based on a third array Cola_Reb 6 5,699 May-13-2022, 06:06 PM
Last Post: deanhystad
Question Change elements of array based on position of input data Cola_Reb 6 3,596 May-13-2022, 12:57 PM
Last Post: Cola_Reb
  Indexing [::-1] to Reverse ALL 2D Array Rows, ALL 3D, 4D Array Columns & Rows Python Jeremy7 8 10,344 Mar-02-2021, 01:54 AM
Last Post: Jeremy7
  Sorting Elements via parameters pointing to those elements. rpalmer 3 3,576 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  4D array with only elements on one side of the diagonal schniefen 0 2,226 Dec-24-2020, 11:32 AM
Last Post: schniefen
  Removing some elements from array based on a condition claw91 0 2,191 Oct-27-2020, 03:42 PM
Last Post: claw91
  Remove specific elements from list with a pattern Xalagy 3 3,738 Oct-11-2020, 07:18 AM
Last Post: Xalagy
  remove elements method not working spalisetty06 4 3,566 Aug-13-2020, 01:17 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020