数组不会在 python 中分配超过 8 个字符
Array won't assign more than 8 characters in python
数组运行异常,我有这段代码:
a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'])
我这样做了:
a[0]="hello there my friend"
结果是:
array(['hello th', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],
dtype='<U8')
到底是怎么回事?
字符串数组默认dtype
会根据最大长度的字符串计算。在你的情况下 dtype='<U8'
.
您必须根据要插入数组的新字符串的长度来定义 dtype
。
你可以这样做:
s = np.array(["hello there my friend"])
a = np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'], \
dtype=s.dtype)
a[0] = "hello there my friend"
print(a)
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
'egypt'], dtype='<U21')
阅读this。
a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'], dtype = 'object')
通过使用 dtype
参数将其更改为一个非常大的数字(例如 100
):
>>> a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],dtype='<U100')
>>> a[0] = "hello there my friend"
>>> a
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
'egypt'],
dtype='<U100')
>>>
或使用:
>>> a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],dtype='<U100')
>>> a.dtype = '<U100'
>>> a[0] = "hello there my friend"
>>> a
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
'egypt'],
dtype='<U100')
>>>
数组运行异常,我有这段代码:
a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'])
我这样做了:
a[0]="hello there my friend"
结果是:
array(['hello th', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],
dtype='<U8')
到底是怎么回事?
字符串数组默认dtype
会根据最大长度的字符串计算。在你的情况下 dtype='<U8'
.
您必须根据要插入数组的新字符串的长度来定义 dtype
。
你可以这样做:
s = np.array(["hello there my friend"])
a = np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'], \
dtype=s.dtype)
a[0] = "hello there my friend"
print(a)
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
'egypt'], dtype='<U21')
阅读this。
a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'], dtype = 'object')
通过使用 dtype
参数将其更改为一个非常大的数字(例如 100
):
>>> a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],dtype='<U100')
>>> a[0] = "hello there my friend"
>>> a
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
'egypt'],
dtype='<U100')
>>>
或使用:
>>> a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'],dtype='<U100')
>>> a.dtype = '<U100'
>>> a[0] = "hello there my friend"
>>> a
array(['hello there my friend', 'gulf', 'egypt', 'hijazi a', 'gulf',
'egypt'],
dtype='<U100')
>>>