我注意到 numpy
中数组的这种违反直觉的行为。我有一个列表列表,我想将其转换为数组:
>>> a = [['abc', 117858348, 117858388, 'def']]
当我将它转换为数组时,它将元素转换为字符串(这很好)但意外地删除了两个中间元素的最后一位:
>>> array(a)
array([['abc', '11785834', '11785838', 'def']],
dtype='|S8')
这是什么原因?有没有办法没有这种行为?将列表的列表转换为数组很方便的原因是为了快速索引某些元素。例如,如果您有一个索引列表 x
到数组 a
中,您可以执行 a[x]
来检索它们。如果 a
是列表的列表,则不能,而必须执行类似 [a[i] for i in x]
的操作。
谢谢。
最佳答案
这很有趣,运行你的例子给我这个:
>>> numpy.asarray([['abc', 117858348, 117858388, 'def']])
array([['abc', '117', '117', 'def']],
dtype='|S3')
我很好奇转换是如何工作的:
>>> help(numpy.asarray)
asarray(a, dtype=None, order=None)
Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
看起来底层类型是从输入数据中推断出来的
,我想知道那是什么意思所以我做了
>>> import inspect
>>> print inspect.getsource(numpy.asarray)
我们得到 return array(a, dtype, copy=False, order=order)
但 numpy.array
是内置的,因此请查看 http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html 处的文档我们得到:
dtype : data-type, optional
The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.
好吧,它看起来尽可能向上转换,所以在我的例子中被向上转换为长度为 3 的字符串,因为那是我在序列中拥有的最长字符串,如果我引入一个更长的字符串,它会向上转换到那个,看起来在我的例子中,它没有正确考虑其他类型的数字长度,这可能是一个错误,我不知道......
你可以只指定一个长字符串序列
>>> numpy.asarray([['abc', 117858348, 117858388, 'defs']], dtype = 'S20')
array([['abc', '117858348', '117858388', 'defs']],
dtype='|S20')
20个字符似乎绰绰有余,虽然它可能会占用更多内存,因此您可以简单地将其设置为最大值...
据我所知,numpy
将值存储为同质类型,这就是为什么在创建数组时所有内容都必须是预先确定的类型的原因。
>>> numpy.__version__
'1.6.1'
$ python --version
Python 2.6.1
$ uname -a
Darwin 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386
希望对您有所帮助。
关于python - 在 numpy 中转换为数组时列表元素的违反直觉的截断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11789363/