## python - combination between elements of two matrices

Question

I have a problem I don't know how to describe it so you understand. I am going to give an example. Let's say we have this array (B) in python:

```
[[ 1 1]
[ 7 11]
[1 20]
[20 1]
[26 11]
[31 11]]
```

The first column represents the users. The second the tags. Now, I want to create a matrix who will have "1s" where edges exist otherwise "0s". We have 5 and 4 different users and tags respectevily, that is a 6*5 matrix.. If I write:

```
zero = np.zeros((6,5,).astype(int) #it needs one more row and column
for line in B:
if line[2]:
zero[line[0],line[1]] = 1
```

the error is:

```
zero[line[0],line[1]] = 1
```

IndexError: index 7 is out of bounds for axis 0 with size 7

Ok, how can I make the combination between two matrices because I want the element "31" to be the fifth row and element "11" the fourth column.

Show source

## Answers ( 2 )

Use pandas and numpy

Staying close to your initial attempt, listed below is a NumPy based approach. We can use

`np.unique(..,return_inverse=1)`

for those two columns to give us unique IDs that could be used as row and column indices respectively for indexing into the output. Thereafter, we would simply initialize the output array and index into it to give us the desired result.Thus, an implementation would be -

Alternatively, a more explicit way to get

`r`

and`c`

would be like so -Sample input, output -