-1

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

Yue Min
  • 11
  • 3
  • What's `data.dtype`? Did you get this from a csv file with genfromtxt? – hpaulj Jan 03 '23 at 03:18
  • It looks like your putting statement is INSIDE the for loop… – Drphoton Jan 03 '23 at 04:27
  • In your previous question you loaded `data` with `genfromtxt` with a compound dtype. That is a structured array, not an array of `tuples`. You access fields by name. `data['price']` https://stackoverflow.com/questions/74976722/genfromtxt-file-returns-filling-values-as-1 – hpaulj Jan 03 '23 at 06:46
  • You get repeats because you `print(datacopy)` each iteration of the loop. `del i` deletes the variable `i`, which is the iteration variable. It does not delete that item from the array. You can use `del alist[2]` to remove an item from a list, but `data` is an array. `del` does not work there. – hpaulj Jan 03 '23 at 07:25
  • I edited my previous answer to show how to select specific items from a structured array. – hpaulj Jan 03 '23 at 07:36

2 Answers2

0

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

the-a-monir
  • 147
  • 1
  • 10
0

Either to use

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

Or

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