Remove Decimals from Array - python

I have 2 arrays containing zeros & ones. I want to perform hstack() on them but not getting the desired output.
Python Code..
import numpy as np
zeros = np.zeros(8)
ones = np.ones(8)
zerosThenOnes = np.hstack((zeros, ones)) # A 1 by 16 array
Current Output..
[ 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1.]
Expected Output..
[ 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 ]
I can't understand what silly mistake I'm doing.

You must tell numpy to return the values as integers
import numpy as np
zeros = np.zeros((8,), dtype=np.int)
ones = np.ones((8,), dtype=np.int)
zerosThenOnes = np.hstack((zeros, ones))
To print out zerosThenOnes like this [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
Use:
print([x for x in zerosThenOnes])
Numpy Zeros

np.hstack((np.zeros(8), np.ones(8))).astype(int)
for np.array output, or
map( int, np.hstack((np.zeros(8), np.ones(8))) )
for list output

Related

How to create a lower diagonal matrix with numpy?

How can I generate a lower diagonal matrix of dynamic size with Numpy?
For example, if the size n of the matrix is 4 I would like to obtain such a matrix:
| 0 0 0 0 |
| 1 0 0 0 |
| 0 1 0 0 |
| 0 0 1 0 |
You could create it, by first creating a matrix with zeros, and then fill in the ones:
import numpy as np
# create matrix with zeros
n=4
mat = np.zeros((n,n))
# create indexes for where the 1s belong
rows = np.arange(1,n)
cols = np.arange(n-1)
# fill in the 1s
mat[rows, cols] = 1
output:
[[0. 0. 0. 0.]
[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]]
I found out the shortest way to be using np.eye:
import numpy as np
n = 4
np.eye(n, k=-1, dtype=int)
The output is:
array([[0, 0, 0, 0],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])

Numpy - Declare a specific nx1 array

I'm using numpy in python , in order to create a nx1 matrix . I want the 1st element of the matrix to be 3 , the 2nd -1 , then the n-1 element -1 again and at the end the n element 3. All the in between elements , i.e. from element 3 to element n-2 should be 0. I've made a drawing of the mentioned matrix , is like this :
I'm fairly new to python and using numpy but seems like a great tool for managing matrices. What I've tried so far is creating the nx1 array (giving n some value) and initializing it to 0 .
import numpy as np
n = 100
I = np.arange(n)
matrix = np.row_stack(0*I)
print("\Matrix is \n",matrix)
Any clues to how i proceed? Or what routine to use ?
Probably the simplest way is to just do the following:
import numpy as np
n = 10
a = np.zeros(n)
a[0] = 3
a[1] = -1
a[len(a)-1] = 3
a[len(a)-2] = -1
>>print(a)
output: [ 3. -1. 0. 0. 0. 0. 0. 0. -1. 3.]
Hope this helps ;)
In [97]: n=10
In [98]: arr = np.zeros(n,int)
In [99]: arr[[0,-1]]=3; arr[[1,-2]]=-1
In [100]: arr
Out[100]: array([ 3, -1, 0, 0, 0, 0, 0, 0, -1, 3])
Easily changed to (n,1):
In [101]: arr[:,None]
Out[101]:
array([[ 3],
[-1],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0],
[ 0],
[-1],
[ 3]])
I guess something that works is :
import numpy as np
n = 100
I = np.arange(n)
matrix = np.row_stack(0*I)
matrix[0]=3
matrix[1]=-1
matrix[n-2]=-1
matrix[n-1]=3
print("\Matrix is \n",matrix)

Producing binary matrix with random lists

so first of all here is my code I have questions about, I feel like the answer will be simple, but I am just too blind to see it
dic = {}
for i in range(0,9):
dic['rand_num{0}'.format(i)] = np.sort(random.sample(range(0,8),5))
mat = np.zeros([8,8])
for rand_num in dic.values():
print(rand_num)
for i in range(0,5):
matrixval = rand_num[i]
#print(matrixval)
for j in range(0,8):
mat[matrixval,j] = 1
print(mat)
I created 8 different lists which will help me determine, where to set a 1 in the matrix.
so eg. if my first list looks like this:
rand_List = [0,3,5,6,7]
the matrix of the first row or column should look like this
matrix = [1, 0, 0, 1, 0, 1, 1, 1]
My position for the matrix value is set in the second loop: for i in range(0,5): matrixval = rand_num[i] . However, as soon I run my code, my matrix just gives me ones instead of ones and zeros. I feel like I have an iteration problem in my last for loop, and I don't know how to fix it.
If anyone could help me, or just give me a hint, how to actually solve this hopefully small mistake of mine, I would really appreciate it.
Hopefully this provides the expected result:
dic = {}
for i in range(0,8):
dic['rand_num{0}'.format(i)] = np.sort(random.sample(range(0,8),5))
mat = np.zeros([8,8])
for j, rand_num in enumerate(dic.values()):
print(rand_num)
for i in range(0,5):
matrixval = rand_num[i]
mat[j,matrixval] = 1
print(mat)
Output:
[1 2 3 5 7]
[0 1 2 5 6]
[0 1 2 3 5]
[1 2 3 4 6]
[0 1 3 4 7]
[1 2 4 5 7]
[0 1 3 4 7]
[1 2 3 4 6]
[[0. 1. 1. 1. 0. 1. 0. 1.]
[1. 1. 1. 0. 0. 1. 1. 0.]
[1. 1. 1. 1. 0. 1. 0. 0.]
[0. 1. 1. 1. 1. 0. 1. 0.]
[1. 1. 0. 1. 1. 0. 0. 1.]
[0. 1. 1. 0. 1. 1. 0. 1.]
[1. 1. 0. 1. 1. 0. 0. 1.]
[0. 1. 1. 1. 1. 0. 1. 0.]]
The dic you are using is not needed. Here is a solution without it.
import random
lists = []
for i in range(0, 9):
lists.append(sorted(random.sample(range(0, 8), 5)))
mat = []
for lst in lists:
arr = [0] * 8
for index in lst:
arr[index] = 1
mat.append(arr)
print(mat)
Outputs:
[[0, 1, 1, 0, 0, 1, 1, 1],
[1, 0, 1, 1, 0, 0, 1, 1],
[1, 1, 1, 1, 0, 0, 0, 1],
[0, 1, 1, 1, 0, 1, 1, 0],
[1, 1, 0, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 0, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 1, 1, 1, 0],
[1, 0, 1, 0, 1, 0, 1, 1]]
You can also use numpy.random.randint to generate your binary 2d array.
import numpy as np
arr = np.random.randint(2, size=(8, 8))
print(arr)
Outputs:
[[1 0 1 0 1 0 1 1]
[0 0 0 0 1 0 1 1]
[1 0 1 1 0 0 1 1]
[1 1 0 1 0 1 1 0]
[0 0 1 0 0 1 1 1]
[1 0 0 0 1 1 1 1]
[1 1 0 1 0 0 1 1]
[1 0 1 0 0 1 0 0]]

Division with numpy matrices that might result in nan

How can I divide two numpy matrices A and B in python when sometimes the two matrices will have 0 on the same cell?
Basically A[i,j]>=B[i,j] for all i, j. I need to calculate C=A/B. But sometimes A[i,j]==B[i,j]==0. And when this happens I need A[i,j]/B[i,j] to be defined as 0.
Is there a simple pythonic way other than going through all the indexes?
You can use the where argument for ufuncs like np.true_divide:
np.true_divide(A, B, where=(A!=0) | (B!=0))
In case you have no negative values (as stated in the comments) and A >= B for each element (as stated in the question) you can simplify this to:
np.true_divide(A, B, where=(A!=0))
because A[i, j] == 0 implies B[i, j] == 0.
For example:
import numpy as np
A = np.random.randint(0, 3, (4, 4))
B = np.random.randint(0, 3, (4, 4))
print(A)
print(B)
print(np.true_divide(A, B, where=(A!=0) | (B!=0)))
[[1 0 2 1]
[1 0 0 0]
[2 1 0 0]
[2 2 0 2]]
[[1 0 1 1]
[2 2 1 2]
[2 1 0 1]
[2 0 1 2]]
[[ 1. 0. 2. 1. ]
[ 0.5 0. 0. 0. ]
[ 1. 1. 0. 0. ]
[ 1. inf 0. 1. ]]
As alternative: Just replace nans after the division:
C = A / B # may print warnings, suppress them with np.seterrstate if you want
C[np.isnan(C)] = 0
You could use a mask with np.where to choose between such a case of A and B being both zeros and otherwise and put out 0 or an elementwise division respectively -
from __future__ import division # For Python 2.x
mask = (A == B) & (A==0)
C = np.where(mask, 0, A/B)
About the mask creation : (A==B) would be the mask of all elements that are equal between A and B and with (A==0) we have a mask of all elements that are zero in A. Thus, with a combined mask of (A == B) & (A==0), we have mask of places where both A and B are zeros. A more simpler version to do the same task and maybe easier to understand would be to check for zeros in both A and B and it would be :
mask = (A==0) & (B==0)
About the use of np.where, its syntax is :
C = np.where(mask, array1, array2)
i.e. we would select elements for assinging into C based on the mask. If the corresponding mask element is True, we pick the corresponding element from array1, else from array2. This is done on elementwise level and thus, we have the output C.
Sample run -
In [48]: A
Out[48]:
array([[4, 1, 4, 0, 3],
[0, 4, 1, 4, 3],
[1, 0, 0, 4, 0]])
In [49]: B
Out[49]:
array([[4, 2, 2, 1, 4],
[2, 1, 2, 4, 2],
[4, 0, 2, 0, 3]])
In [50]: mask = (A == B) & (A==0)
In [51]: np.where(mask, 0, A/B)
Out[51]:
array([[ 1. , 0.5 , 2. , 0. , 0.75],
[ 0. , 4. , 0.5 , 1. , 1.5 ],
[ 0.25, 0. , 0. , inf, 0. ]])

Filling a 2D list with user input where value of column increases by 1 iteratively

I asks the user to input the values of ROW to fill a 2D list. The value of column will be iterativley increase by 1.
list2D = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
user input = [1,3,0,2] ##indexes of rows as well as values
i.e:
0th column the row = 1
1 column row = 3
2 column row = 0
3 column row = 2
So the new list will be:
newList = [[0,0,**0**,0],[1,0,0,0],[0,0,0,2],[0,3,0,0]]
How to do this?
list2D = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
user_input = [1,3,0,2]
for col,row in enumerate(user_input):
list2D[row][col] = row
print(list2D)
# [[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 2], [0, 3, 0, 0]]
or, if you do not wish to modify list2D:
import copy
list2D = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
user_input = [1,3,0,2]
newList = copy.deepcopy(list2D)
for col,row in enumerate(user_input):
newList[row][col] = row
or, using numpy:
import numpy as np
list2D = np.zeros((4,4))
user_input = [1,3,0,2]
list2D[user_input,range(4)] = user_input
print(list2D)
# [[ 0. 0. 0. 0.]
# [ 1. 0. 0. 0.]
# [ 0. 0. 0. 2.]
# [ 0. 3. 0. 0.]]

Categories