npross
npross

Reputation: 1888

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??!

Upvotes: 3

Views: 12928

Answers (2)

mhawke
mhawke

Reputation: 87084

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.

Upvotes: 3

Xorgon
Xorgon

Reputation: 520

This is likely due to how you are creating your numpy array.

The following code works fine:

import numpy as np

p = np.array([[" asdf ", " asdf " ], [" afhffh hfhf ", " a "]])
print(type(p))
print(p)

p = np.char.strip(p)
print(p)

And outputs:

<class 'numpy.ndarray'>
[[' asdf ' ' asdf ']
 [' afhffh hfhf ' ' a ']]
[['asdf' 'asdf']
 ['afhffh hfhf' 'a']]

Upvotes: -1

Related Questions