Deleting List Elements Based on Condition

Deleting list elements based on condition

list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]]
list_1 = [item for item in list_1 if item[2] >= 5 or item[3] >= 0.3]

You can also use if not (item[2] < 5 and item[3] < 0.3) for the condition if you want.

Remove elements from lists based on condition

using del is not the same as removing an element from a list.
consider the following example

>>> x=1
>>> y=2
>>> lst = [x,y]
>>> del x
>>> print(lst)
[1, 2]
>>> lst.remove(x)
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'x' is not defined
>>> lst.remove(y)
>>> print(lst)
[1]
>>> print(y)
2

as you can see using del on the variable sharing the pointer to the element in the list
only deleted the pointer leaving the list as it was.
remove did the opposite. it removed the element from the list but did not delete the variable pointer.

as for fixing the problem: you should not directly remove from a list while iterating.

IMO the best fix is using list comprehension to make a new list with only the wanted elements and replacing the old one:

for line in lines['col1']:
line = [item for item in line.split() if item >= THRESHOLD
# line = ' '.join(line)

P.S.
added the commented line if you wish to return the line to a string

How to delete list elements based on condition in Python

If you just want to delete [0,0] you can do it like this:

a = [[(0, 0, 0), 337.94174378689814],
[(0, 0, 1), 339.92776762374007],
[(0, 0, 2), 338.78632729456444],
[(0, 1, 0), 344.85997106879347],
[(0, 1, 1), 331.6819890120493],
[0, 0]]

while True:
try:
a.remove([0, 0])
except ValueError:
break

Or use filter:

a = list(filter(lambda x: x != [0, 0], a))

remove elements from a list based on condition in pandas dataframe

Try:

mask = df.joined_month.eq(df.current_month)
df.loc[mask, "dates"] = df[mask].apply(
lambda x: [v for v in x["dates"] if v >= x.joined_day], axis=1
)

print(df)

Prints:

   id  joined_day  joined_month  current_month         dates
0 1 15 9 9 [16, 17, 18]
1 2 12 9 9 [12, 23]
2 3 9 9 9 [9]
3 4 10 9 9 []

Remove elements from a list by condition

We need to extract the column within the loop. LDF is a list of data.frame/tibble, thus LDF$Value doesn't exist

i1 <- sapply(LDF, function(x) sum(x$Value)) > 0
LDF[i1]

-output

[[1]]
# A tibble: 18 x 2
Date Value
<date> <dbl>
1 2021-05-18 120000
2 2021-05-20 40000
3 2021-05-31 55000
4 2021-05-31 -11.4
5 2021-06-01 -115092.
6 2021-06-09 30000
7 2021-06-17 98400
8 2021-07-01 1720
9 2021-07-01 50000
10 2021-07-01 -50063.
11 2021-07-12 -2503.
12 2021-07-13 -20022.
13 2021-08-09 28619.
14 2021-08-25 45781.
15 2021-09-01 14954.
16 2021-09-10 -6017.
17 2021-09-15 -3311.
18 2021-09-16 -140373.

To check the elements that are deleted, negate (!) the logical vector and check

which(!i1)

gives the position

LDF[!i1]

Or may use Filter as well

Filter(\(x) sum(x$Value) >0, LDF)

Or with keep from purrr

library(purrr)
keep(LDF, ~ sum(.x$Value) > 0)

Or the opposite is discard

discard(LDF, ~ sum(.x$Value) > 0)

How to remove element of list based on condition in the sublist

Just slicing:

s = ''.join(b for a,b,c in list_of_list)
list_of_list[s.find('|'):s.rfind('|')+1]

Remove element from list based on condition

You could do like this:

l = [0.22, 0.6, 0.94, 1.28, 1.66, 2., 2.38, 2.72, 3.04, 3.42, 3.76, 4.2, 4.58, 
4.94, 5.32, 5.68, 6.08, 6.42, 6.8, 7.22, 7.54]
l2 = [l[0]]

for elm in l:
if abs(elm - l2[-1]) > 1:
l2.append(elm)

print(l2)

remove adjacent list elements based on condition?

Don't remove elements from a list you're iterating over. You could use a slice for both inputs of zip(): that will create a copy so you won't run into the same problem.

for i, j in zip(a[:-1], a[1:]):
if abs(i-j) <= 0.20:
a.remove(j)

which gives

[183.4, 182.1, 182.75]

Alternatively, invert the condition and build a new list.

a_new = a[0:1] # Create a new list with the first element of a
for i, j in zip(a, a[1:]):
if abs(i-j) > 0.20: # Append j to the new list if the difference is greater
a_new.append(j)

Note that this doesn't take into account the case when multiple consecutive pairs of elements are within your threshold. For example: a = [183.4, 183.3, 183.15, 182.1, 182.75], this will remove both 183.3 and 183.15.

If you want the minimum difference between consecutive elements in your result to be 0.2, simply compare with the last element of a_new and add the current element if it satisfies your condition.

a = [183.4, 183.3, 183.15, 182.1, 182.75]
a_new = a[0:1]

for i in a[1:]:
if abs(a_new[-1] - i) > 0.2:
a_new.append(i)

And this gives [183.4, 183.15, 182.1, 182.75]

Remove element from a list based on condition in pandas dataframe

You can filter both sides in mask and for remove 40 in list use lambda function:

df = pd.DataFrame(a)

m = df['B'].ne('FOOTBALL')
df.loc[m, 'C'] = df.loc[m, 'C'].apply(lambda x: [y for y in x if y!=40])
print (df)
A B C
0 1 FOOTBALL [5, 10, 15, 40]
1 2 BASKETBALL [1, 4]
2 3 HANDBALL [20, 10]
3 4 VOLLEYBALL [10]

Alternative:

m = df['B'].ne('FOOTBALL')
df.loc[m, 'C'] = [[y for y in x if y!=40] for x in df.loc[m, 'C']]

Deleting elements of a list based on a condition

You can use collections.Counter:

from collections import Counter
import itertools
A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']]
c = Counter(itertools.chain(*A))
new_a = [[b for b in i if c[b] > 2] for i in A]

Output:

[['b', 'c'], ['b'], ['c', 'e'], ['c', 'e'], ['b', 'c', 'e']]


Related Topics



Leave a reply



Submit