Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of "zip()" in Python's numpy?

I am trying to do the following but with numpy arrays:

x = [(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)] normal_result = zip(*x) 

This should give a result of:

normal_result = [(0.1, 0.1, 0.1, 0.1, 0.1), (1., 2., 3., 4., 5.)] 

But if the input vector is a numpy array:

y = np.array(x) numpy_result = zip(*y) print type(numpy_result) 

It (expectedly) returns a:

<type 'list'> 

The issue is that I will need to transform the result back into a numpy array after this.

What I would like to know is what is if there is an efficient numpy function that will avoid these back-and-forth transformations?

like image 656
TimY Avatar asked Oct 05 '12 10:10

TimY


People also ask

What is zip in NumPy in Python?

Python zip() Function The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

Does zip work in NumPy?

If we want to bind or zip the data of different array then we can go for zip function in python of NumPy. This function eliminates the need of class object if not required. We can easily map our data with any number of the array and this can be done very easily with the use of the zip() function.

How do I zip a NumPy array?

NumPy Zip With the list(zip()) Function. If we have two 1D arrays and want to zip them together inside a 2D array, we can use the list(zip()) function in Python. This approach involves zipping the arrays together inside a list. The list(zip(a,b)) function takes the arrays a and b as an argument and returns a list.

What is zip Python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.


1 Answers

You can just transpose it...

>>> a = np.array([(0.1, 1.), (0.1, 2.), (0.1, 3.), (0.1, 4.), (0.1, 5.)]) >>> a array([[ 0.1,  1. ],        [ 0.1,  2. ],        [ 0.1,  3. ],        [ 0.1,  4. ],        [ 0.1,  5. ]]) >>> a.T array([[ 0.1,  0.1,  0.1,  0.1,  0.1],        [ 1. ,  2. ,  3. ,  4. ,  5. ]]) 
like image 91
Jon Clements Avatar answered Oct 18 '22 20:10

Jon Clements