Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 1st, 2012  |  syntax: None  |  size: 0.74 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Typecasting a numpy matrix into a string in python
  2. xx = np.matrix([[1.2,3.4],[5.4,6.7],[9.8, 5.2]])
  3. zz = np.matrix([[str(ele) for ele in a] for a in np.array(xx)])
  4.        
  5. >>> xx
  6. matrix([[ 1.2,  3.4],
  7.         [ 5.4,  6.7],
  8.         [ 9.8,  5.2]])
  9. >>> zz
  10. matrix([['1.2', '3.4'],
  11.         ['5.4', '6.7'],
  12.         ['9.8', '5.2']],
  13.        dtype='|S3')
  14.        
  15. In [45]: a = np.random.normal(size=(3,3))
  16.  
  17. In [46]: a
  18. Out[46]:
  19. array([[ 0.64552723, -0.4329958 , -1.84342512],
  20.        [ 0.83197804, -0.03053034,  0.22560254],
  21.        [ 0.61356459, -1.60778048, -1.51859134]])
  22.  
  23. In [47]: a.astype('|S8')
  24. Out[47]:
  25. array([['0.645527', '-0.43299', '-1.84342'],
  26.        ['0.831978', '-0.03053', '0.225602'],
  27.        ['0.613564', '-1.60778', '-1.51859']],
  28.       dtype='|S8')