如何在numpy中将字符串值分配给数组? [英] How to assign a string value to an array in numpy?

查看:100
本文介绍了如何在numpy中将字符串值分配给数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将字符串分配给这样的数组时:

When I try to assign a string to an array like this:

CoverageACol[0,0] = "Hello" 

我收到以下错误

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    CoverageACol[0,0] = "hello"
ValueError: setting an array element with a sequence.

但是,分配整数不会导致错误:

However, assigning an integer does not result in an error:

CoverageACol[0,0] = 42

CoverageACol是一个numpy数组.

CoverageACol is a numpy array.

请帮助!谢谢!

推荐答案

由于NumPy的数组为

You get the error because NumPy's array is homogeneous, meaning it is a multidimensional table of elements all of the same type. This is different from a multidimensional list-of-lists in "regular" Python, where you can have objects of different type in a list.

常规Python:

>>> CoverageACol = [[0, 1, 2, 3, 4],
                    [5, 6, 7, 8, 9]]

>>> CoverageACol[0][0] = "hello"

>>> CoverageACol
    [['hello', 1, 2, 3, 4], 
     [5, 6, 7, 8, 9]]

NumPy:

>>> from numpy import *

>>> CoverageACol = arange(10).reshape(2,5)

>>> CoverageACol
    array([[0, 1, 2, 3, 4],
           [5, 6, 7, 8, 9]])

>>> CoverageACol[0,0] = "Hello" 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/home/biogeek/<ipython console> in <module>()

ValueError: setting an array element with a sequence.

因此,这取决于您要实现的目标,为什么要将字符串存储在用数字填充的其余数组中?如果这确实是您想要的,则可以将NumPy数组的数据类型设置为字符串:

So, it depends on what you want to achieve, why do you want to store a string in an array filled for the rest with numbers? If that really is what you want, you can set the datatype of the NumPy array to string:

>>> CoverageACol = array(range(10), dtype=str).reshape(2,5)

>>> CoverageACol
    array([['0', '1', '2', '3', '4'],
           ['5', '6', '7', '8', '9']], 
           dtype='|S1')

>>> CoverageACol[0,0] = "Hello"

>>> CoverageACol
    array([['H', '1', '2', '3', '4'],
         ['5', '6', '7', '8', '9']], 
         dtype='|S1')

请注意,仅分配了Hello的第一个字母.如果您希望分配整个单词,则需要设置数组-协议类型字符串:

Notice that only the first letter of Hello gets assigned. If you want the whole word to get assigned, you need to set an array-protocol type string:

>>> CoverageACol = array(range(10), dtype='a5').reshape(2,5)

>>> CoverageACol: 
    array([['0', '1', '2', '3', '4'],
           ['5', '6', '7', '8', '9']], 
           dtype='|S5')

>>> CoverageACol[0,0] = "Hello"

>>> CoverageACol
    array([['Hello', '1', '2', '3', '4'],
           ['5', '6', '7', '8', '9']], 
           dtype='|S5')

这篇关于如何在numpy中将字符串值分配给数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆