1

I have a matrix of strings. How do I add a column to the front, like

[['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']]
Saullo G. P. Castro
  • 53,388
  • 26
  • 170
  • 232
siamii
  • 21,999
  • 26
  • 89
  • 139

1 Answers1

1

The answer in @Paul's comments explains it all. Adding here for completeness.

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')
Community
  • 1
  • 1
mg007
  • 2,818
  • 22
  • 27