Numpy append in a for loop using zip

Viewed 218

I have two different lists containing respectively some x and z values. From these two I need to take only some values and distribute x and z over to different rows.

So far I tried this:

import numpy as np

x = [1, 3, 6, 10, 15, 20]
z = [3, 5, 6, 9, 20, 25]

for x_val, z_val in zip(x, z):
    if x_val > 6 and z_val > 6:
        a = np.append(x_val, z_val)

From which I would expect 10, 15, 20 for the x and 9, 20, 25 for z but I only get the last values (20 and 25) on the same row.

a = [20, 25]
2 Answers

You always overwrite your array with last pair in line

a = np.append(x_val, z_val)

Create a array at the beginning, before for loop and then append to it in above line.

So complete working code (without numpy as it is not needed for simple arrays) is

x = [1, 3, 6, 10, 15, 20]
z = [3, 5, 6, 9, 20, 25]

a = []
for x_val, z_val in zip(x, z):
    if x_val > 6 and z_val > 6:
        a.append((x_val, z_val))

To be honest, I'm not 100% clear on your expected output (perhaps update the question to include). I've given a few different options below:

Option 1, using numpy:

a = np.array(x+z)
result = list(zip(*a[a>6].reshape(2, -1)))

Output:

[(10, 9), (15, 20), (20, 25)]

Option 2, if you'd rather not use numpy, you can do:

result = [(x_, z_) for x_, z_ in zip(x, z) if all([x_>6, z_>6])]

Output:

[(10, 9), (15, 20), (20, 25)]

Option 3, another output format can be done as:

result = list(zip(*[(x_, z_) for x_, z_ in zip(x, z) if all([x_>6, z_>6])]))

Output:

[(10, 15, 20), (9, 20, 25)]
Related