【发布时间】:2018-03-01 12:34:58
【问题描述】:
我已经创建了一个二维 Numpy 字符串数组,如下所示:
a = np.full((2, 3), '#', dtype=np.unicode)
print(a)
输出是:
array([['#', '#', '#'], ['#', '#', '#']], dtype=`'<U1'`)
我想用'?'填充它在宽度为 1 的所有边上。我期望输出为:
array([
['?', '?', '?', '?', '?'],
['?', '#', '#', '#', '?'],
['?', '#', '#', '#', '?'],
['?', '#', '#', '#', '?'],
['?', '?', '?', '?', '?']],
dtype=`'<U1')
我尝试了以下方法:
b = np.pad(a, ((1, 1), (1, 1)), 'constant', constant_values=(('?', '?'), ('?', '?')))
但这会产生以下错误:
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/numpy/lib/arraypad.py", line 1357, in pad
cast_to_int=False)
File "/usr/lib/python3/dist-packages/numpy/lib/arraypad.py", line 1069, in _normalize_shape
return tuple(tuple(axis) for axis in arr.tolist())
AttributeError: 'tuple' object has no attribute 'tolist'
类似的代码适用于整数。我对字符串做错了什么?
【问题讨论】:
-
这只是一个
numpy错误——它的实现细节假设了关于数组的过于具体的条件,并且当它无法继续时它会转储一个无用的消息。正如@Kasramvd 所示,您可以通过创建自己的填充函数来规避它。 -
我在 1.14 中遇到了另一个错误。请注意,某些模式涉及最大值和插值。 “恒定”模式可能只是其中之一的特例。对于像这样的简单填充来说,这太过分了。
标签: python string python-3.x numpy