Reducing size of a character array in Numpy
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 colu开发者_开发百科mn to the minimum required size, in the above case |S4
?
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')
>>> x = np.array(['a ','bb ','cccc '])
>>> x = np.array([s.strip() for s in x])
>>> x
array(['a', 'bb', 'cccc'],
dtype='|S4')
精彩评论