当我尝试将字符串分配给这样的数组时:
CoverageACol[0,0] = "Hello"
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
CoverageACol[0,0] = "hello"
ValueError: setting an array element with a sequence.
Run Code Online (Sandbox Code Playgroud)
但是,分配整数不会导致错误:
CoverageACol[0,0] = 42
Run Code Online (Sandbox Code Playgroud)
CoverageACol是一个numpy数组.
请帮忙!谢谢!
Bio*_*eek 15
你得到错误是因为NumPy的数组是同构的,这意味着它是一个多维表格的所有相同类型的元素.这与"常规"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]]
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
那么,这取决于你想要实现的目标,为什么你要将一个字符串存储在一个数组中?如果这真的是你想要的,你可以将NumPy数组的数据类型设置为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')
Run Code Online (Sandbox Code Playgroud)
请注意,只Hello分配了第一个字母.如果要分配整个单词,则需要设置数组协议类型字符串:
>>> 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')
Run Code Online (Sandbox Code Playgroud)
CoverageACol = numpy.array([["a","b"],["c","d"]],dtype=numpy.dtype('a16'))
Run Code Online (Sandbox Code Playgroud)
这使得ConerageACol成为长度为16的字符串(a)数组.
| 归档时间: |
|
| 查看次数: |
35771 次 |
| 最近记录: |