【问题标题】:How to assign a string value to an array in numpy?如何将字符串值分配给numpy中的数组?
【发布时间】:2011-10-23 09:34:15
【问题描述】:

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

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.

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

CoverageACol[0,0] = 42

CoverageACol 是一个 numpy 数组。

请帮忙!谢谢!

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    需要设置arraydata type

    CoverageACol = numpy.array([["a","b"],["c","d"]],dtype=numpy.dtype('a16'))
    

    这使得 ConerageACol 成为长度为 16 的字符串 (a) 数组。

    【讨论】:

      【解决方案2】:

      您收到错误是因为 NumPy 的数组是 homogeneous, meaning it is a multidimensional table of elements all of the same type。这与“常规”Python 中的多维列表列表不同,您可以在列表中包含不同类型的对象。

      常规 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 数组的数据类型设置为字符串:

      >>> 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 的第一个字母被分配。如果要分配整个单词,则需要设置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')
      

      【讨论】:

      • 感谢您的详细解释!
      • 设置 dtype=object 也可以:stackoverflow.com/questions/14639496/…
      • 在您的行中overageACol = array(range(10), dtype=str).reshape(2,5)。是否可以将dtype 更改为listdict
      猜你喜欢
      • 2021-12-12
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多