在numpy数组中剥离空格

时间:2017-10-10 00:03:34

标签: python string numpy whitespace

我有一个相当不错的外观,无法找到一个简单的/一行方式来删除numpy数组中的空格::

print(type(p))
print(p)

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

要::

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

尝试

np.char.strip(p)

结果

TypeError: string operation on non-string array

因此,这是伪装的名单吗?

小帮忙??!

2 个答案:

答案 0 :(得分:3)

你有一组数组,所以迭代它们。使用剥离元素创建一个新集合,并创建一个新数组:

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

这使用集合理解来创建带有剥离元素的新集合。原始数组在列表推导中迭代,然后将其输入np.array()以创建新数组。

答案 1 :(得分:-1)

这可能是由于你如何创建你的numpy数组。

以下代码可以正常使用:

import numpy as np

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

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

输出:

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