tags:

views:

120

answers:

2

Given a character array:

In [21]: x = np.array(['a     ','bb   ','cccc    '])

One can remove the whitespace using:

In [22]: np.char.strip(x)
Out[22]: 
array(['a', 'bb', 'cccc'], 
      dtype='|S8')

but is there a way to also shrink the width of the column to the minimum required size, in the above case |S4?

+1  A: 

Do you just want to change the data type?

import numpy as NP
a = NP.array(["a", "bb", "ccc"])
a 
# returns array(['a', 'bb', 'ccc'], dtype='|S3')
a = NP.array(a, dtype="|S8")   # change dtype
# returns array(['a', 'bb', 'ccc'], dtype='|S8')

a = NP.array(a, dtype="|S3")   # change it back
# returns array(['a', 'bb', 'ccc'], dtype='|S3')    
doug
A: 
>>> x = np.array(['a     ','bb   ','cccc    '])
>>> x = np.array([s.strip() for s in x])
>>> x
array(['a', 'bb', 'cccc'], 
      dtype='|S4')
mtrw