python - 两个矩阵的元素之间的组合

时间:2016-12-22 13:52:43

标签: python algorithm numpy matrix

我有一个问题我不知道如何描述它让你理解。 我要举一个例子。 让我们说我们在python中有这个数组(B):

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

第一列代表用户。第二个标签。 现在,我想创建一个将拥有" 1s"否则边缘存在" 0s"。 我们有5个和4个不同的用户和标签,分别是6 * 5矩阵.. 如果我写:

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

错误是:

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

IndexError:索引7超出了轴0的大小为7

好的,我怎样才能在两个矩阵之间进行组合,因为我想要元素" 31"成为第五行和元素" 11"第四栏。

2 个答案:

答案 0 :(得分:3)

使用pandas和numpy

>>>import numpy as np
>>>import pandas as pd
>>> tagsArray = np.unique([1,11,20,1,11,11])
>>> userArray = np.unique([1,7,20,26,31])
>>> aa = [[ 1,1],[ 7, 11],[1, 20],[20, 1],[26, 11],[31, 11]]
>>> df = pd.DataFrame(index=userArray,columns=tagsArray)
>>> for s in aa:
...     df.loc[s[0],s[1]] = 1
...
>>> df.fillna(0,inplace=True)
>>> df
     1    11   20
1     1  NaN    1
7   NaN    1  NaN
20    1  NaN  NaN
26  NaN    1  NaN
31  NaN    1  NaN

答案 1 :(得分:0)

接近您的初始尝试,下面列出的是基于NumPy的方法。我们可以对这两列使用np.unique(..,return_inverse=1)来为我们提供唯一的ID,这些ID可以分别用作行索引和列索引以索引输出。此后,我们只需初始化输出数组并将其索引到其中,以便为我们提供所需的结果。

因此,实现将是 -

r,c = [np.unique(i,return_inverse=1)[1] for i in B.T]
out = np.zeros((r.max()+1,c.max()+1),dtype=int)
out[r,c] = 1

或者,获得rc的更明确的方法就是这样 -

r = np.unique(B[:,0],return_inverse=1)[1]
c = np.unique(B[:,1],return_inverse=1)[1]

示例输入,输出 -

In [27]: B  # Input array
Out[27]: 
array([[ 1,  1],
       [ 7, 11],
       [ 1, 20],
       [20,  1],
       [26, 11],
       [31, 11]])

In [28]: out  # Output
Out[28]: 
array([[1, 0, 1],
       [0, 1, 0],
       [1, 0, 0],    r = np.unique(B[:,0],return_inverse=1)[1]
c = np.unique(B[:,1],return_inverse=1)[1]
       [0, 1, 0],
       [0, 1, 0]])
相关问题