gpt4 book ai didi

python - Numpy 字符串数组用字符串填充

转载 作者:行者123 更新时间:2023-12-01 02:06:08 25 4
gpt4 key购买 nike

我创建了一个 2d 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'

类似的代码适用于整数。我对字符串做错了什么?

最佳答案

您不能用字符串文字填充数组。相反,正如提到的in documentation您可以使用 pad_with 函数,如下所示:

In [79]: def pad_with(vector, pad_width, iaxis, kwargs):
...: pad_value = kwargs.get('padder', '?')
...: vector[:pad_width[0]] = pad_value
...: vector[-pad_width[1]:] = pad_value
...: return vector
...:

In [80]:

In [80]: np.pad(a, 1, pad_with)
Out[80]:
array([['?', '?', '?', '?', '?'],
['?', '#', '#', '#', '?'],
['?', '#', '#', '#', '?'],
['?', '#', '#', '#', '?'],
['?', '?', '?', '?', '?']], dtype='<U1')

请注意,在 pad_with 函数的 pad_value = kwargs.get('padder', '?') 行中,您应该使用默认填充值,以防没有填充np.pad 的调用者提供的参数。您可以将预期的 padder 作为关键字参数传递给函数。

In [82]: np.pad(a, 1, pad_with, padder='*')
Out[82]:
array([['*', '*', '*', '*', '*'],
['*', '#', '#', '#', '*'],
['*', '#', '#', '#', '*'],
['*', '#', '#', '#', '*'],
['*', '*', '*', '*', '*']], dtype='<U1')

关于python - Numpy 字符串数组用字符串填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com