Double elements in Python Numpy Array [duplicate] - python

This question already has answers here:
Repeating each element of a numpy array 5 times
(2 answers)
Closed 4 years ago.
I'm trying to copy every element into a 2d array in Python such that it doubles the size of the array and adds the element directly after the element that it intends to copy.
For example:
[[1,2,3],
[4,5,6],
[7,8,9]]
becomes
[[1,1,2,2,3,3],
[4,4,5,5,6,6],
[7,7,8,8,9,9]]
Can anyone help with this problem? Thanks!

You can use np.repeat(..) [numpy-doc] for this:
>>> import numpy as np
>>> np.repeat(a, 2, axis=1)
array([[1, 1, 2, 2, 3, 3],
[4, 4, 5, 5, 6, 6],
[7, 7, 8, 8, 9, 9]])
We thus repeat, for the second axis (axis=1) the elements two times.
We can also use list-comprehension, but given that the data has the same time, using numpy is faster, and more declarative:
times2 = [[xi for x in row for xi in [x, x]] for row in a]
This the produces:
>>> [[xi for x in row for xi in [x, x]] for row in a]
[[1, 1, 2, 2, 3, 3], [4, 4, 5, 5, 6, 6], [7, 7, 8, 8, 9, 9]]

Related

Numpy Array: Slice several values at every step

I am trying to extract several values at once from an array but I can't seem to find a way to do it in a one-liner in Numpy.
Simply put, considering an array:
a = numpy.arange(10)
> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
I would like to be able to extract, say, 2 values, skip the next 2, extract the 2 following values etc. This would result in:
array([0, 1, 4, 5, 8, 9])
This is an example but I am ideally looking for a way to extract x values and skip y others.
I thought this could be done with slicing, doing something like:
a[:2:2]
but it only returns 0, which is the expected behavior.
I know I could obtain the expected result by combining several slicing operations (similarly to Numpy Array Slicing) but I was wondering if I was not missing some numpy feature.
If you want to avoid creating copies and allocating new memory, you could use a window_view of two elements:
win = np.lib.stride_tricks.sliding_window_view(a, 2)
array([[0, 1],
[1, 2],
[2, 3],
[3, 4],
[4, 5],
[5, 6],
[6, 7],
[7, 8],
[8, 9]])
And then only take every 4th window view:
win[::4].ravel()
array([0, 1, 4, 5, 8, 9])
Or directly go with the more dangerous as_strided, but heed the warnings in the documentation:
np.lib.stride_tricks.as_strided(a, shape=(3,2), strides=(32,8))
You can use a modulo operator:
x = 2 # keep
y = 2 # skip
out = a[np.arange(a.shape[0])%(x+y)<x]
Output: array([0, 1, 4, 5, 8, 9])
Output with x = 2 ; y = 3:
array([0, 1, 5, 6])

Appending to the rows and columns to Multi dimensional Arrays Numpy Python

I am trying to append to create a multi dimensional array where it inputs 4 random numbers per row. The code below does not work. How would I be able to fix it?
import numpy as np
import random
Array = np.array([[]])
for i in range(3):
for k in range(4):
Array[i][k]= np.append(Array[i][k], random.randint(0,9))
Expected Output:
[[1,3,4,8],
[2,3,6,4],
[7,4,1,5],
[8,3,1,1]]
Don't do this. It is highly inefficient to try to create an array like this incrementally using np.append. If you must do something like this, use a listand then convert the resulting list to anumpy.ndarray` later.
However, in this case, you simply want:
>>> import numpy as np
>>> np.random.randint(0, 10, (3,4))
array([[0, 3, 7, 4],
[6, 4, 2, 2],
[4, 4, 0, 6]])
Or perhaps:
>>> np.random.randint(0, 10, (4,4))
array([[8, 8, 2, 7],
[3, 7, 2, 1],
[5, 5, 5, 5],
[6, 2, 7, 9]])
Note, np.random.randint has an exclusive end, so if you want to draw from numbers [0, 9] you need to use 9+1 as the end.

Connecting an array of numpys [duplicate]

This question already has answers here:
concatenate numpy arrays which are elements of a list
(2 answers)
Closed 2 years ago.
I have a list of numpys of the same length each. for example:
my_list = [np.array([2, 3, 5, 5]),
np.array([5, 4, 1, 4]),
np.array([8, 4, 5, 1]),
np.array([7, 4, 5, 1])]
I want to turn the list into 2d numpy:
[[2, 3, 5, 5],
[5, 4, 1, 4],
[8, 4, 5, 1],
[7, 4, 5, 1]]
The following code does perform the operation but in a sloppy manner.
The result is also not arranged in the desired order:
combined = []
for i in my_list :
if len(combined) == 0:
combined = i
else:
combined = np.vstack((i,combined))
print(combined)
What needs to be changed to get the desired result?
The most straightforward way
np.vstack(my_list)
or
np.concatenate(my_list).reshape(len(my_list),-1)
Simply doing np.array(my_list) can get the job done.

Apply same permutation for every row in a 2D numpy array

To permute a 1D array A I know that you can run the following code:
import numpy as np
A = np.random.permutation(A)
I have a 2D array and want to apply exactly the same permutation for every row of the array. Is there any way you can specify the numpy to do that for you?
Generate random permutations for the number of columns in A and index into the columns of A, like so -
A[:,np.random.permutation(A.shape[1])]
Sample run -
In [100]: A
Out[100]:
array([[3, 5, 7, 4, 7],
[2, 5, 2, 0, 3],
[1, 4, 3, 8, 8]])
In [101]: A[:,np.random.permutation(A.shape[1])]
Out[101]:
array([[7, 5, 7, 4, 3],
[3, 5, 2, 0, 2],
[8, 4, 3, 8, 1]])
Actually you do not need to do this, from the documentation:
If x is a multi-dimensional array, it is only shuffled along its first
index.
So, taking Divakar's array:
a = np.array([
[3, 5, 7, 4, 7],
[2, 5, 2, 0, 3],
[1, 4, 3, 8, 8]
])
you can just do: np.random.permutation(a) and get something like:
array([[2, 5, 2, 0, 3],
[3, 5, 7, 4, 7],
[1, 4, 3, 8, 8]])
P.S. if you need to perform column permutations - just do np.random.permutation(a.T).T. Similar things apply to multi-dim arrays.
It depends what you mean on every row.
If you want to permute all values (regardless of row and column), reshape your array to 1d, permute, reshape back to 2d.
If you want to permutate each row but not shuffle the elements among the different columns you need to loop trough the one axis and call permutation.
for i in range(len(A)):
A[i] = np.random.permutation(A[i])
It can probably done shorter somehow but that is how it can be done.

How to transpose a matrix in python without zip [duplicate]

This question already has answers here:
Matrix Transpose in Python [duplicate]
(19 answers)
Closed 9 years ago.
I was wondering how you could change the user input in python into a list, or better yet, a matrix, just as you would convert it to an integer by using int(input).
>>> L = [[1,2,3], [4,5,6], [7,8,9]]
>>> [[x[i] for x in L] for i in range(len(L[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
or
>>> zip(*L)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
or
>>> import numpy as np
>>> L = np.arange(1, 10).reshape((3, 3))
>>> L
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> L.transpose()
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
array([[1,2,3], [4,5,6], [7,8,9]]).T will do what you want, if you're using numpy.
list comprehensions should fit the bill quite nicely. Here's the general function:
def transpose(the_array):
return [[the_array[j][i] for j in range(0, len(the_array[i]))] for i in range(0, len(the_array))]

Categories