Home > Mobile >  How to remove tuple from an array?
How to remove tuple from an array?

Time:01-03

The array is a 1D array:

[('2007-Q2', 'ANG MO KIO', '1-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '2-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '3-ROOM', 172000) ('2022-Q1', 'YISHUN', '4-ROOM', 450000) ('2022-Q1', 'YISHUN', '5-ROOM', 582500) ('2022-Q1', 'YISHUN', 'EXEC', 800000)]

I would like to remove the tuples containing the '-1'

i'm currently using the del function

datacopy = np.copy(data)
print(datacopy)

for i in datacopy:
    if i[3] == -1:
        del i
    print(datacopy)

but i end up getting repeats of the same array:

[('2007-Q2', 'ANG MO KIO', '1-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '2-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '3-ROOM', 172000) ('2022-Q1', 'YISHUN', '4-ROOM', 450000) ('2022-Q1', 'YISHUN', '5-ROOM', 582500) ('2022-Q1', 'YISHUN', 'EXEC', 800000)] [('2007-Q2', 'ANG MO KIO', '1-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '2-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '3-ROOM', 172000) ('2022-Q1', 'YISHUN', '4-ROOM', 450000) ('2022-Q1', 'YISHUN', '5-ROOM', 582500) ('2022-Q1', 'YISHUN', 'EXEC', 800000)] [('2007-Q2', 'ANG MO KIO', '1-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '2-ROOM', -1) ('2007-Q2', 'ANG MO KIO', '3-ROOM', 172000) ('2022-Q1', 'YISHUN', '4-ROOM', 450000) ('2022-Q1', 'YISHUN', '5-ROOM', 582500) ('2022-Q1', 'YISHUN', 'EXEC', 800000)]

what i would like to get in return is

[('2007-Q2', 'ANG MO KIO', '3-ROOM', 172000) ('2022-Q1', 'YISHUN', '4-ROOM', 450000) ('2022-Q1', 'YISHUN', '5-ROOM', 582500) ('2022-Q1', 'YISHUN', 'EXEC', 800000)]

CodePudding user response:

Try this one:

newList= [x for x in datacopy if x[3] != -1] 

Here, x will be each of your tuple, and if x[3] != -1 will work as filter regarding your condition

CodePudding user response:

Either to use

filtered_data = [tuple for tuple in data if tuple[3] != -1]

Or

filtered_data = filter(lambda x: x[3] != -1, data)

  • Related