在一行打印`numpy.ndarray`

M'v*_*'vy 5 python formatting numpy multidimensional-array

在使用scipy/numpy时,我确实获得了存储到的信息 numpy.ndarray

>>> a
array([[ 0.15555605,  0.51031528,  0.84580176,  0.06722675],
       [ 0.60556045,  0.62721023, -0.48979983, -0.04152777],
       [-0.78044785,  0.58837543, -0.21146041, -0.13568023],
       [ 0.        ,  0.        ,  0.        ,  1.        ]])
>>> print(a)
[[ 0.15555605  0.51031528  0.84580176  0.06722675]
 [ 0.60556045  0.62721023 -0.48979983 -0.04152777]
 [-0.78044785  0.58837543 -0.21146041 -0.13568023]
 [ 0.          0.          0.          1.        ]]
Run Code Online (Sandbox Code Playgroud)

如何在一行上打印结果?

我已经检查过:

>>> numpy.get_printoptions()
{'precision': 8, 'threshold': 1000, 'edgeitems': 3, 'linewidth': 75, 'suppress': False, 'nanstr': 'nan', 'infstr': 'inf', 'formatter': None}
Run Code Online (Sandbox Code Playgroud)

但即使设置linewidth为1000也不会改变这一点.有没有办法更改该类型的显示格式?

是否也可以在每个数字之间添加逗号(如数组显示但没有周围array(...))?

小智 13

要将a打印numpy.array到一行,您可以将其转换为具有内置函数的列表numpy.tolist()

例:

import numpy as np

arr = np.array(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
Run Code Online (Sandbox Code Playgroud)

简单打印数组:

print(arr)
[[1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

numpy.tolist():相比:

print(array.tolist())
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)

  • `array.tolist()` 和 `list(arr)` 不一样。`print(list(arr))` 给出 `[array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]` (5认同)

MSe*_*ert 7

NumPy 提供了几种自定义打印的方法,例如np.array2string.

对于这个答案,我假设您有这样一个数组:

>>> import numpy as np
... arr = np.array([[ 0.15555605,  0.51031528,  0.84580176,  0.06722675],
...                 [ 0.60556045,  0.62721023, -0.48979983, -0.04152777],
...                 [-0.78044785,  0.58837543, -0.21146041, -0.13568023],
...                 [ 0.        ,  0.        ,  0.        ,  1.        ]])
Run Code Online (Sandbox Code Playgroud)
  • 如果要显示所有需要的项目,请确保thresholdnp.inf.
  • 如果您想,作为分隔符,您可以设置separator','.

但是它没有删除换行符的选项,只是

  • max_line_width它给出了最里面维度在一行中打印的字符数。因此,当您设置时,它适用于一维阵列,max_line_width=np.inf但不适用于 ND 阵列。

幸运的是,它返回一个可以操作的字符串,例如通过删除所有换行符:

>>> np.array2string(arr, threshold=np.inf, max_line_width=np.inf, separator=',').replace('\n', '')
'[[ 0.15555605, 0.51031528, 0.84580176, 0.06722675], [ 0.60556045, 0.62721023,-0.48979983,-0.04152777], [-0.78044785, 0.58837543,-0.21146041,-0.13568023], [ 0.        , 0.        , 0.        , 1.        ]]'
Run Code Online (Sandbox Code Playgroud)

或者使用正则表达式删除所有空格:

>>> import re
>>> re.sub(r'\s+', '', np.array2string(arr, threshold=np.inf, max_line_width=np.inf, separator=','))
'[[0.15555605,0.51031528,0.84580176,0.06722675],[0.60556045,0.62721023,-0.48979983,-0.04152777],[-0.78044785,0.58837543,-0.21146041,-0.13568023],[0.,0.,0.,1.]]'
Run Code Online (Sandbox Code Playgroud)

同意这些并不是真正的“短”,它们也比转换为listwith.tolist()然后转换为字符串慢,但它可能是一个不错的选择,特别是如果您想自定义打印结果而不创建(可能很大)不必要的列表。