insert 2d arrays into one 3d array - python

I'm trying to insert some 2d array to a 3d one..
the code is running well but I have difficulties with the insert command.
all of the 2d arrays are correct but when I insert them the 3d array int updating (only zeros)
def binarySeqs (seq_list):
"""taking dna sequences and returning a 3d matrix """
lenght=len(seq_list[0])
num_of_seq=len(seq_list)
for i in seq_list:
if lenght!=len(i):
raise ValueError ("Invalid list of sequences")
for i in seq_list:
if set(i).issubset("ACGT")==False :
raise ValueError ("Invalid list of sequences")
basedict={'A':0 , 'T':1 ,'C':2 , 'G':3}
my_array=np.zeros(( num_of_seq, 4, lenght))
#print(my_array.shape)
for l in seq_list:
dmat=seqBinary(l)
#print(dmat)
for i in range((num_of_seq)):
#print(i)
np.insert(my_array ,i , dmat, axis=0 )
return my_array

numpy.insert is not in-place operation, it does return changed array, consider following example:
import numpy as np
a = np.array([1,2,3])
b = np.insert(a, 1, [5])
print(a) # [1 2 3]
print(b) # [1 5 2 3]
So you should assign changed array back to variable, i.e. instead of
np.insert(my_array ,i , dmat, axis=0 )
do
my_array = np.insert(my_array ,i , dmat, axis=0 )

Related

How to get a numpy array from a list

I have a list
list_num = [4 , 5 , 6]
How to convert it into a numpy array with of shape ( , 3) as when using the function
res = np.array(list_num).shape
output is ( ,3 )
If printing the res variable shape, the result is (3,) and not (,3), so I will understand you have mistyped that.
Just removing the .shape from res, as imM4TT user had cited, the variable will be like you need: res = [4 5 6].
If printing the res.shape, you will obtain (3,).
If you really want to reshape to an array with size (,3), its necessary to use what executable user had cited, the reshape function:
res = res.reshape(1,3)

Python:Initialize and append data to 3d numpy array of unknown length beforehand

I want create 3d array with unknown length and append to the array as follows:
a = np.array([])
for n in range(1,3):
data=np.full((2,3),n)
a = np.append(a,data,axis=0)
print(a)
The expected output is:
[[[1,1,1]
[1,1,1]]
[[2,2,2]
[2,2,2]]]
However, I got an error:
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 2 dimension(s)
How to declare an empty 3d numpy array with unknown length and append to it?
It's better performance-wise (and easier) to create a list of your 2d arrays, then to call numpy.stack():
a = []
for n in range(1, 3):
data = np.full((2, 3), n)
a.append(data)
a = np.stack(a)
print(a)
print(a.shape) # <- (2, 2, 3)
You can also append to the list (a) 2d arrays in a list-of-lists structure (meaning, they don't have to be numpy arrays) and call np.stack() on that "list of lists of lists", would work too.

Python - Easy and Fast Way to Divide Values in a 2D List by a Single Value

For example I have a 2D list of 2x2 dimension stored in a variable r.
12 24
36 48
I want to divide every value in the list by 2. An easy slow way to do this is to iterate through each row and column and divide it by 2.
rows = 2
columns = 2
for x in range(rows):
for y in range(columns):
r[x][y] = r[x][y]/2
Is there an easy and fast way to divide each values in a 2D list to a specific value other than the manual approach? I tried the code below but it throws an error:
s = r /2
Error:
TypeError: unsupported operand type(s) for /: 'list' and 'int'
You can use numpy library to achieve the result you want. it uses vectorization so its the fastest way to do the operation.
Try this:
import numpy as np
arr = np.array(r) # --> initialize with 2d array
arr = arr / 2 # --> Now each element in the 2d array gets divided by 2
For Example:
arr = np.array([[1, 2], [2, 3]]) # --> initialize with 2d array
arr = arr / 2 # --> divide by the scalar
print(arr)
Output:
[[0.5 1. ]
[1. 1.5]]
Looks like there is even a section in official documentation about nested list comprehensions:
https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions
i.e.
>>> r = [[12,24],[36,48]]
>>> [[i/2 for i in a] for a in r]
[[6.0, 12.0], [18.0, 24.0]]
import numpy as np
x=np.array(2D_list)
x=x/2

to make a llist that have all zeros except the one column which should be value 1

can anyone help on this?
if i try this code,
a = np.array([2,1,5],[2,5,3])
b = np.zeros_like(a)
c=b[np.arange(len(a)), a.argmax()] = 1
print(c)
It gives errortoo many Indices for array
my motive is to make a list that gives me all columns zeros except the one that is highest in the input Numpy array,and make it '1'.
output shoud be([0,0,1],[0,1,0])
Code:
matrix = np.array([[2, 1, 5], [2, 5, 3]])
imax = matrix.argmax(1)
n_labels = np.size(matrix, 1)
onehot = np.eye(n_labels)[imax]
How it works, line by line:
Define the numpy array.
Get the index of the maximum value in each row.
Get the size of the matrix's row, N.
Create a NxN matrix (lets call it M), in which all the values are zero, except the main diagonal, which is 1. For each value i from step 2, select the row i from this new matrix M.

create numpy array with varying shape

I want to create a numpy array in order to fill it with numpy arrays. for example:
a = [] (simple array or numpy array)
b = np.array([[5,3],[7,9],[3,8],[2,1]])
a = np.concatenate([a,b])
c = np.array([[1,2],[2,9],[3,0]])
a = np.concatenate([a,c])
I would like to do so because I have wav files from which I extract some features so I can't read from 2 files concurrently but iteratively.
How can I create an empty ndarray with the second dimension fixed e.g. a.shape = (x,2) or how can I concatenate the arrays even without the creation of a "storage" array ?
Actually there are 2 options.
The first one is:
a = np.empty((0, 2)) , which creates an empty np array with the first dimension varying.
The second is to create an empty array
a = [] , append the np arrays in the array and then use np.vstack to concatenate them all together in the end. The latter the most efficient option.
You have to had brackets in concatenate function:
b = np.array([[5,3],[7,9],[3,8],[2,1]])
c = np.array([[1,2],[2,9],[3,0]])
a = np.concatenate([b,c])
Output:
[[5 3]
[7 9]
[3 8]
[2 1]
[1 2]
[2 9]
[3 0]]

Categories