 # efficient way of making a list of pairs from an array in numpy

• Last Update :
• Techknowledgy :

The cleanest way of doing this I can think of would be:

```>>> x = np.arange(12).reshape(3, 4) >>>
x
array([
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]
]) >>>
n = x.shape - 1 >>>
y = np.repeat(x, (n, ) + (1, ) * n, axis = 1) >>>
y
array([
[0, 0, 0, 1, 2, 3],
[4, 4, 4, 5, 6, 7],
[8, 8, 8, 9, 10, 11]
]) >>>
y.reshape(-1, 2, n).transpose(0, 2, 1).reshape(-1, 2)
array([
[0, 1],
[0, 2],
[0, 3],
[4, 5],
[4, 6],
[4, 7],
[8, 9],
[8, 10],
[8, 11]
])```

This will make two copies of the data, so it will not be the most efficient method. That would probably be something like:

```>>> y = np.empty((x.shape, n, 2), dtype = x.dtype) >>>
y[..., 0] = x[: , 0, None] >>>
y[..., 1] = x[: , 1: ] >>>
y.shape = (-1, 2) >>>
y
array([
[0, 1],
[0, 2],
[0, 3],
[4, 5],
[4, 6],
[4, 7],
[8, 9],
[8, 10],
[8, 11]
])```

Like `Jaimie`, I first tried a `repeat` of the 1st column followed by reshaping, but then decided it was simpler to make 2 intermediary arrays, and `hstack` them:

```x = np.array([
[0, 1, 2, 3],
[1, 2, 7, 9],
[2, 1, 5, 2]
])
m, n = x.shape
x1 = x[: , 0].repeat(n - 1)[: , None]
x2 = x[: , 1: ].reshape(-1, 1)
np.hstack([x1, x2])```

producing

```array([
[0, 1],
[0, 2],
[0, 3],
[1, 2],
[1, 7],
[1, 9],
[2, 1],
[2, 5],
[2, 2]
])```

Suppose the `numpy` array is

```arr = np.array([
[0, 1, 2, 3],
[1, 2, 7, 9],
[2, 1, 5, 2]
])```

You can get the array of pairs as

```import itertools
m, n = arr.shape
new_arr = np.array([x
for i in range(m)
for x in itertools.product(a[i, 0: 1], a[i, 1: n])
])```

The output would be

```array([
[0, 1],
[0, 2],
[0, 3],
[1, 2],
[1, 7],
[1, 9],
[2, 1],
[2, 5],
[2, 2]
])```

Suggestion : 2

Python’s Numpy module provides a function numpy.array() to create a Numpy Array from an another array like object in python like list or tuple etc or any nested sequence like list of list,,On passing a list of list to numpy.array() will create a 2D Numpy Array by default. But if we want to create a 1D numpy array from list of list then we need to merge lists of lists to a single list and then pass it to numpy.array() i.e.,In this article we will discuss how to create a Numpy Array from a sequence like list or tuple etc. Also, how to create a 2D numpy Numpy Array from nested sequence like lists of lists.,We created the Numpy Array from the list or tuple. While creation numpy.array() will deduce the data type of the elements based on input passed.But we can check the data type of Numpy Array elements i.e.

To install the python’s numpy module on you system use following command,

`pip install numpy`

To use numpy module we need to import it i.e.

`import numpy as np`

Python’s Numpy module provides a function numpy.array() to create a Numpy Array from an another array like object in python like list or tuple etc or any nested sequence like list of list,

`numpy.array(object, dtype = None, copy = True, order = 'K', subok = False, ndmin = 0)`

Output:

`[1 2 3 4 5 6 7 8 9]`

Similar to above example, we can directly pass the tuple to the numpy.array() to create a Numpy Array object,

```# Create ndArray from a tuple
npArray = np.array((11, 22, 33, 44, 55, 66, 77, 88))

print('Contents of the ndArray : ')
print(npArray)```

Suggestion : 3

NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren’t homogeneous.,The ease of implementing mathematical formulas that work on arrays is one of the things that make NumPy so widely used in the scientific Python community.,You can index and slice NumPy arrays in the same ways you can slice Python lists.,Be aware that these visualizations are meant to simplify ideas and give you a basic understanding of NumPy concepts and mechanics. Arrays and array operations are much more complicated than are captured here!

`conda install numpy`
`pip install numpy`
`import numpy as np`
```>>> a = np.arange(6) >>>
a2 = a[np.newaxis,: ] >>>
a2.shape(1, 6)```
`>>> a = np.array([1, 2, 3, 4, 5, 6])`
```>>> a = np.array([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
])```

Suggestion : 4

The easiest way to create an array is to use the array function. This accepts any sequence-like object (including other arrays) and produces a new NumPy array containing the passed data. For example, a list is a good candidate for conversion:,Whenever you see “array”, “NumPy array”, or “ndarray” in the text, with few exceptions they all refer to the same thing: the ndarray object.,NumPy array indexing is a rich topic, as there are many ways you may want to select a subset of your data or individual elements. One-dimensional arrays are simple; on the surface they act similarly to Python lists:,As a simple example, suppose we wished to evaluate the function sqrt(x^2 + y^2) across a regular grid of values. The np.meshgrid function takes two 1D arrays and produces two 2D matrices corresponding to all pairs of (x, y) in the two arrays:

```In: data1 = [6, 7.5, 8, 0, 1]

In: arr1 = np.array(data1)

In: arr1
Out: array([6., 7.5, 8., 0., 1.])```
```In: arr1 = np.array([1, 2, 3], dtype = np.float64)

In: arr2 = np.array([1, 2, 3], dtype = np.int32)

In: arr1.dtype In: arr2.dtype
Out: dtype('float64') Out: dtype('int32')```
```In: arr = np.array([
[1., 2., 3.],
[4., 5., 6.]
])

In: arr
Out:
array([
[1., 2., 3.],
[4., 5., 6.]
])

In: arr * arr In: arr - arr
Out: Out:
array([
[1., 4., 9.], array([
[0., 0., 0.],
[16., 25., 36.]
])[0., 0., 0.]
])```
```In: arr = np.arange(10)

In: arr
Out: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In: arr
Out: 5

In: arr[5: 8]
Out: array([5, 6, 7])

In: arr[5: 8] = 12

In: arr
Out: array([0, 1, 2, 3, 4, 12, 12, 12, 8, 9])```
```In: arr[1: 6]
Out: array([1, 2, 3, 4, 64])```
```In: names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])

In: data = np.random.randn(7, 4)

In: names
Out:
array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'],
dtype = '|S4')

In: data
Out:
array([
[-0.048, 0.5433, -0.2349, 1.2792],
[-0.268, 0.5465, 0.0939, -2.0445],
[-0.047, -2.026, 0.7719, 0.3103],
[2.1452, 0.8799, -0.0523, 0.0672],
[-1.0023, -0.1698, 1.1503, 1.7289],
[0.1913, 0.4544, 0.4519, 0.5535],
[0.5994, 0.8174, -0.9297, -1.2564]
])```

Suggestion : 5

There are a number of ways of creating multidimensional NumPy arrays. The most straightforward way is to convert a list to an array using NumPy’s array function, which we demonstrate here:,NumPy has a number of functions for creating arrays. We focus on four (or five or six, depending on how you count!). The first of these, the array function, converts a list to an array:,The result is that each element of the two arrays are added. Similar results are obtained for subtraction, multiplication, and division:,There are a number of other functions for creating arrays. For example, a 3 row by 4 column array or array with all the elements filled with 1 can be created using the ones function introduced earlier.

```In: a = "My dog's name is"
In: b = "Bingo"```
```In: c = a + " " + b
In: c
Out: "My dog's name is Bingo"```
```In: d = "927"
In: e = 927```
```In: a = [0, 1, 1, 2, 3, 5, 8, 13]
In: b = [5., "girl", 2 + 0 j, "horse", 21]```
```In: b
Out: 5.0

In: b
Out: 'girl'

In: b
Out: (2 + 0 j)```
```In: b
Out: 21

In: b[-1]
Out: 21

In: b[-2]
Out: 'horse'```

Suggestion : 6

Last Updated : 21 Feb, 2022,GATE CS 2021 Syllabus

Python provides support of itertools standard library which is used to create iterators for efficient looping. The library provides support for various kinds of iterations, in groups, sorted order, etc. The permutations() functions of this library are used to get through all possible orderings of the list of elements, without any repetitions. The permutations() functions have the following syntax:

`itertools.permutations(lst, r)`

Output :

```(2, 2)
(2, 2)
(2, 2)
(2, 2)
(2, 2)
(2, 2)```

Suggestion : 7

Computation on NumPy arrays can be very fast, or it can be very slow. The key to making it fast is to use vectorized operations, generally implemented through NumPy's universal functions (ufuncs). This section motivates the need for NumPy's ufuncs, which can be used to make repeated calculations on array elements much more efficient. It then introduces many of the most common and useful arithmetic ufuncs available in the NumPy package.,NumPy's ufuncs feel very natural to use because they make use of Python's native arithmetic operators. The standard addition, subtraction, multiplication, and division can all be used:,This can even be used with array views. For example, we can write the results of a computation to every other element of a specified array:,Vectorized operations in NumPy are implemented via ufuncs, whose main purpose is to quickly execute repeated operations on values in NumPy arrays. Ufuncs are extremely flexible – before we saw an operation between a scalar and an array, but we can also operate between two arrays:

```import numpy as np
np.random.seed(0)

def compute_reciprocals(values):
output = np.empty(len(values))
for i in range(len(values)):
output[i] = 1.0 / values[i]
return output

values = np.random.randint(1, 10, size = 5)
compute_reciprocals(values)```
`array([0.16666667, 1., 0.25, 0.25, 0.125])`
```big_array = np.random.randint(1, 100, size = 1000000) %
timeit compute_reciprocals(big_array)```
`1 loop, best of 3: 2.91 s per loop`
```print(compute_reciprocals(values))
print(1.0 / values)```
```[0.16666667 1. 0.25 0.25 0.125]
[0.16666667 1. 0.25 0.25 0.125]```