I am new to python and stack overflow. I need to create a binary matrix that the value takes 1 if the customers exist in a given list. For example: assume a list as [4,5,8]. i need a 10x10 matrix with all zero excepts matrix[4,5],matrix[5,4], matrix[5,8],matrix[8,5] and matrix[4,8], matrix[8,4] are 1. Is there an easy way to do this? Thank you.
CodePudding user response:
You have:
data = [4, 5, 8]
You calculate:
matrix = [[int(c in data and r in data and c != r) for c in range(10)] for r in range(10)]
You get:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
The solution shown above uses zero-based indexing.
CodePudding user response:
You can do this with numpy
as vectorize and without use of for-loop
like below:
arr = [4,5,8]
idx = np.array(np.meshgrid(arr,arr)).T.reshape(-1,2)
#romove (4,4) , (5,5) , (8,8)
idx = idx[idx[:,0] != idx[:,1]]
mtx = np.zeros((10,10))
mtx[idx[:,0], idx[:,1]] = 1
print(mtx)
Output:
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 1. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]