Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripping whitespaces in a numpy array

I've had a pretty decent look around and can't find an easy/one line way to strip whitespaces in a numpy array::

print(type(p))
print(p)

<class 'numpy.ndarray'>
[{' SPL', 'GPU', 'bcc'} {'ANZ ', 'ROI'} {'ANZ', 'bcc'}
 {'GPU', '  ANZ   ', 'bcc'} {'bcc ', ' SPL'}]

to::

[{'SPL', 'GPU', 'bcc'} {'ANZ', 'ROI'} {'ANZ', 'bcc'}
 {'GPU', 'ANZ', 'bcc'} {'bcc', 'SPL'}]

Trying

np.char.strip(p)

results in

TypeError: string operation on non-string array

Thus, is this a list in disguise?

Little help??!

like image 356
npross Avatar asked Jun 21 '26 11:06

npross


1 Answers

You have an array of sets, so iterate over them. create a new set with the stripped elements, and create a new array:

p = np.array([{item.strip() for item in s} for s in p])

This uses a set comprehension to create new sets with the stripped elements. The original array is iterated over within a list comprehension, which is then fed into np.array() to create a new array.

like image 197
mhawke Avatar answered Jun 24 '26 02:06

mhawke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!