【问题标题】:How can I assign a strin to an element in numpy arrays如何将字符串分配给 numpy 数组中的元素
【发布时间】:2021-12-12 07:50:15
【问题描述】:

当我将字符串分配给数组时,它只会拾取第一个字符,我需要整个字符串。我是不是用错了方法?

import numpy

i=0

def func(name,number,array,i):
    arry[i,0]=number
    array[i,1]=name
    print(array)

People= numpy.zeros([5,2],dtype=str)

func("qwe","123",People,i)

#this is the output    
 [['1' 'q']
 ['' '']
 ['' '']
 ['' '']
 ['' '']]
#this is the desired output
[['123' 'qwe']
 ['' '']
 ['' '']
 ['' '']
 ['' '']]

【问题讨论】:

  • String dtype 具有特定的大小。使用dtype='U10' or something like that. Look at the People.dtype`。

标签: arrays numpy variable-assignment


【解决方案1】:

分配 people 数组来保存对象而不是字符串:

People= numpy.zeros([5,2], dtype=object)

print(func("qwe","123",People,i))
# [['123' 'qwe']
#  ['' '']
#  ['' '']
#  ['' '']
#  ['' '']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多