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']]
3
  • 1
    same as any other array: stackoverflow.com/questions/5064822/… Commented Apr 22, 2013 at 20:38
  • @Paul how do I intialize the column of strings? the es Commented Apr 22, 2013 at 20:38
  • np.array([['a','b'],['a','b']], dtype=str) Commented Apr 22, 2013 at 20:39

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.