2011-08-09 53 views
5

當我嘗試將一個字符串分配給一個這樣的數組:如何將字符串值分配給numpy中的數組?

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數組。

請幫忙!謝謝!

回答

11

因爲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陣列的數據類型設置爲字符串:,只有Hello第一個字母被分配

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

通知。如果你想讓整個單詞得到分配,你需要設置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') 
+1

謝謝你的詳細解釋! – Moose

+1

設置'dtype = object'也起作用:https://stackoverflow.com/questions/14639496/python-numpy-array-of-arbitrary-length-strings –

+0

在你的行中overageACol = array(range(10),dtype = STR).reshape(2,5)'。是否可以將'dtype'改成'list'或'dict'? –

4

您需要設置arraydata type

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

這使得ConerageACol長度爲16

相關問題