因爲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')
謝謝你的詳細解釋! – Moose
設置'dtype = object'也起作用:https://stackoverflow.com/questions/14639496/python-numpy-array-of-arbitrary-length-strings –
在你的行中overageACol = array(range(10),dtype = STR).reshape(2,5)'。是否可以將'dtype'改成'list'或'dict'? –