2

I have a one dimensional numpy array, for example looking like :

[500.774994, 2837.050049, 492.190002, 2840.379883, 475.800018, 2828.725098]

Assuming the size of the array is a multiple of 2, how could i convert it into an array of pairs of the following shape ?

[(500.774994, 2837.050049), (492.190002, 2840.379883), (475.800018, 2828.725098)]

or

[[500.774994, 2837.050049], [492.190002, 2840.379883], [475.800018, 2828.725098]]

2 Answers 2

5

You just need a reshape:

a = np.array([500.774994, 2837.050049, 492.190002, 2840.379883, 475.800018, 2828.725098])

a.reshape(-1, 2)

array([[ 500.774994, 2837.050049],
       [ 492.190002, 2840.379883],
       [ 475.800018, 2828.725098]])
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

x = [500.774994, 2837.050049, 492.190002, 2840.379883, 475.800018, 2828.725098]
list(zip(x[::2],x[1:]))

Output:

[(500.774994, 2837.050049),
 (492.190002, 492.190002),
 (475.800018, 2840.379883)]

4 Comments

Maybe check if len(x) may be divided by two? Just for safety...
No need since zip does not require 2 arrays to have same length
it works, thanks @ExplodingGayFish ! (what a crazy name ^^).
@MartinSteinborn dont worry i already handle this case, and to focus only on the transformation matter i specified we were assuming it was dividable by 2 in the post :) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.