I would like to expand a list of arrays into a single array, so for example:
a = [array([1,2,3]), array([4,5,6]), array([7,8,9,])]
To become:
a = [array([1,2,3,4,5,6,7,8,9])]
How do I do this?
One option is to convert list to np.array and then flatten inside the list:
>>> import numpy as np
>>> arr = [np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9,])]
>>> [np.array(arr).flatten()]
[array([1, 2, 3, 4, 5, 6, 7, 8, 9])]
Try using
list.extend
It will work
Maybe you want this
from numpy import array
k=[array([1,2,3]), array([4,5,6]), array([7,8,9,])]
l=[]
for i in range(len(k)):
l.extend(k[i])
print(array(l))
Output:
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
You can use reshape of Numpy to do it:-
a=[[1,2,3],[3,4,5],[6,7,8]]
print("Before:" , a)
import numpy as np
a=np.reshape(a,9)
print("After:",a)
The output:
Before: [[1, 2, 3], [3, 4, 5], [6, 7, 8]]
After: [1 2 3 3 4 5 6 7 8]
Hope this is what you want.
Related
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.
I've got a numpy matrix that has 2 rows and N columns, e.g. (if N=4):
[[ 1 3 5 7]
[ 2 4 6 8]]
The goal is create a string 1,2,3,4,5,6,7,8.
Merge the rows such that the elements from the first row have the even (1, 3, ..., N - 1) positions (the index starts from 1) and the elements from the second row have the odd positions (2, 4, ..., N).
The following code works but it isn't really nice:
xs = []
for i in range(number_of_cols):
xs.append(nums.item(0, i))
ys = []
for i in range(number_of_cols):
ys.append(nums.item(1, i))
nums_str = ""
for i in range(number_of_cols):
nums_str += '{},{},'.format(xs[i], ys[i])
Join the result list with a comma as a delimiter (row.join(','))
How can I merge the rows using built in functions (or just in a more elegant way overall)?
Specify F order when flattening (or ravel):
In [279]: arr = np.array([[1,3,5,7],[2,4,6,8]])
In [280]: arr
Out[280]:
array([[1, 3, 5, 7],
[2, 4, 6, 8]])
In [281]: arr.ravel(order='F')
Out[281]: array([1, 2, 3, 4, 5, 6, 7, 8])
Joining rows can be done this way :
>>> a = np.arange(12).reshape(3,4)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> np.hstack([a[i,:] for i in range(a.shape[0])])
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
Then it's simple to convert this array into string.
Here's one way of doing it:
out_str = ','.join(nums.T.ravel().astype('str'))
We are first transposing the array with .T, then flattening it with .ravel(), then converting each element from int to str, and then applying `','.join() to combine all the str elements
Trying it out:
import numpy as np
nums = np.array([[1,3,5,7],[2,4,6,8]])
out_str = ','.join(nums.T.ravel().astype('str'))
print (out_str)
Result:
1,2,3,4,5,6,7,8
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]]
For example, I have a 2D Array with dimensions 3 x 3.
[1 2 7
4 5 6
7 8 9]
And I want to remove all columns which contain 7 - so first and third, outputting a 3 x 1 matrix of:
[2
5
8]
How do I go about doing this in python? I want to apply it to a large matrix of n x n dimensions.
Thank You!
#Creating array
x = np.array([[1, 2, 7],[4,5, 6],[7,8,9]])
x
Out[]:
array([[1, 2, 7],
[4, 5, 6],
[7, 8, 9]])
#Deletion
a = np.delete(x,np.where(x ==7),axis=1)
a
Out[]:
array([[2],
[5],
[8]])
numpy can help you do this!
import numpy as np
a = np.array([1, 2, 7, 4, 5, 6, 7, 8, 9]).reshape((3, 3))
b = np.array([col for col in a.T if 7 not in col]).T
print(b)
If you don't actually want to delete parts of the original matrix, you can just use boolean indexing:
a
Out[]:
array([[1, 2, 7],
[4, 5, 6],
[7, 8, 9]])
a[:, ~np.any(a == 7, axis = 1)]
Out[]:
array([[2],
[5],
[8]])
you can use argwhere for column index and then delete.
import numpy
a = numpy.array([[5, 2, 4],[1, 7, 3],[1, 2, 7]])
index = numpy.argwhere(a==7)
y = numpy.delete(a, index, axis=1)
print(y)
A = np.array([[1,2,7],[4,5,6],[7,8,9]])
for i in range(0,3):
... B=A[:,i]
... if(7 in B):
... A=np.delete(A,i,1)
I have a one dimensional array from which I would like to create a new array containing only parts of user wished sizes of the beginning, the middle, and the end of the former.
import numpy
a = range(10)
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
I would like b to be equal to:
b
array([0, 1, 2, 5, 6, 7, 9])
Assuming that b is constructed of the concatenation of a[:3], a[5:6], and a[9].
I can of course use things such as np.concatenate, but is there a way to do that with slicing method, or anything else in one line?
One way is to create an array of the indices you want to index your array with:
import numpy
a = numpy.arange(10)
i = numpy.array([0, 1, 2, 5, 6, 7, 9]) # An array containing the indices you want to extract
print a[i] # Index the array based on the indices you selected
OUTPUT
[0 1 2 5 6 7 9]
I found a solution:
import numpy as np
a = range(10)
b = np.hstack([a[:3], a[5:6], a[9])
b
array([0, 1, 2, 5, 6, 7, 9])
but does slicing allow such a move?