数组在python中分配的字符数不能超过8

时间:2019-05-23 08:28:54

标签: python arrays numpy numpy-ndarray

数组的行为很奇怪,我有以下代码:

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')

到底是怎么回事?

3 个答案:

答案 0 :(得分:1)

将基于最大长度的字符串计算字符串数组的默认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')

答案 1 :(得分:1)

阅读this

a=np.array(['dfdfdfdf', 'gulf', 'egypt', 'hijazi a', 'gulf', 'egypt'], dtype = 'object')

答案 2 :(得分:1)

使用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')
>>>