在另一个数组中通过索引表示字符串矩阵

时间:2016-10-03 19:12:35

标签: arrays numpy matrix

我想使用numpy在edges中用nodes代表nodes = np.array('A B C D E'.split()) edges = np.array([['A', 'B'], ['A', 'C'], ['B', 'C'], ['B', 'E'], ['D', 'E']]) 中的字符串。

np.array([[0, 1],
          [0, 2],
          [1, 2],
          [1, 4],
          [3, 4]])

所需输出

dict

明显的非优化方法是创建dict并将字符串替换为import json import requests url = 'http://localhost:8086/write?db=mydb' files ={'file' : open('sample.json', 'rb')} r = requests.post(url, files=files) print(r.text) 的值。

1 个答案:

答案 0 :(得分:2)

您可以使用layout_collapseParallaxMultiplier -

np.searchsorted(nodes,edges)

示例运行 -

In [17]: nodes
Out[17]: 
array(['A', 'B', 'C', 'D', 'E'], 
      dtype='|S1')

In [18]: edges
Out[18]: 
array([['A', 'B'],
       ['A', 'C'],
       ['B', 'C'],
       ['B', 'E'],
       ['D', 'E']], 
      dtype='|S1')

In [19]: np.searchsorted(nodes,edges)
Out[19]: 
array([[0, 1],
       [0, 2],
       [1, 2],
       [1, 4],
       [3, 4]])

如果nodes没有排序,我们需要使用sorter参数,如示例运行的修改版本所示 -

In [44]: nodes
Out[44]: 
array(['E', 'D', 'C', 'B', 'A'], 
      dtype='|S1')

In [45]: edges
Out[45]: 
array([['A', 'B'],
       ['A', 'C'],
       ['B', 'C'],
       ['B', 'E'],
       ['D', 'E']], 
      dtype='|S1')

In [46]: sidx = nodes.argsort()

In [47]: sidx[np.searchsorted(nodes,edges,sorter=sidx)]
Out[47]: 
array([[4, 3],
       [4, 2],
       [3, 2],
       [3, 0],
       [1, 0]])
相关问题