简体   繁体   中英

How to remove tuple from an array?

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)]

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

Either to use

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

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM