如何将一列字符串添加到numpy字符串矩阵?

时间:2013-04-22 20:36:10

标签: python string matrix numpy

我有一个字符串矩阵。如何在前面添加列,例如

[['a','b'],   ==>   [['e','a','b'],
 ['c','d'],          ['e','c','d'],
 ['a','b'],   ==>    ['e','a','b'],
 ['c','d'],          ['e','c','d'],
 ['a','b'],   ==>    ['e','a','b'],
 ['c','d']]          ['e','c','d']]

1 个答案:

答案 0 :(得分:1)

answer in @Paul's comments解释了这一切。在此处添加完整性。

In [1]: a = np.tile(np.array([["a","b"], ["c","d"]]), (3,1))

In [2]: a 
Out[2]: array([['a', 'b'],
       ['c', 'd'],
       ['a', 'b'],
       ['c', 'd'],
       ['a', 'b'],
       ['c', 'd']], 
      dtype='<U1')

In [3]: e = np.tile("e", a.shape[0])[None].T # REF: https://stackoverflow.com/a/11885718/155813

In [4]: e 
Out[4]: array([['e'],
       ['e'],
       ['e'],
       ['e'],
       ['e'],
       ['e']], 
      dtype='<U1')

In [5]: np.hstack([e, a]) 
Out[5]: array([['e', 'a', 'b'],
       ['e', 'c', 'd'],
       ['e', 'a', 'b'],
       ['e', 'c', 'd'],
       ['e', 'a', 'b'],
       ['e', 'c', 'd']], 
      dtype='<U1')