当我打印一个numpy数组时,我得到了一个截断的表示,但我想要完整的数组。

>>> numpy.arange(10000)
array([   0,    1,    2, ..., 9997, 9998, 9999])

>>> numpy.arange(10000).reshape(250,40)
array([[   0,    1,    2, ...,   37,   38,   39],
       [  40,   41,   42, ...,   77,   78,   79],
       [  80,   81,   82, ...,  117,  118,  119],
       ..., 
       [9880, 9881, 9882, ..., 9917, 9918, 9919],
       [9920, 9921, 9922, ..., 9957, 9958, 9959],
       [9960, 9961, 9962, ..., 9997, 9998, 9999]])

当前回答

这是对neoks答案的轻微修改(删除了向set_printoptions传递额外参数的选项)。

它展示了如何使用contextlib.contextmanager轻松创建这样的contextmanager,只需更少的代码行:

import numpy as np
from contextlib import contextmanager

@contextmanager
def show_complete_array():
    oldoptions = np.get_printoptions()
    np.set_printoptions(threshold=np.inf)
    try:
        yield
    finally:
        np.set_printoptions(**oldoptions)

在您的代码中,可以这样使用:

a = np.arange(1001)

print(a)      # shows the truncated array

with show_complete_array():
    print(a)  # shows the complete array

print(a)      # shows the truncated array (again)

其他回答

听起来你在用numpy。

如果是这种情况,您可以添加:

import numpy as np
np.set_printoptions(threshold=np.nan)

这将禁用拐角打印。有关详细信息,请参阅本NumPy教程。

numpy.savetxt

numpy.savetxt(sys.stdout, numpy.arange(10000))

或者如果需要字符串:

import StringIO
sio = StringIO.StringIO()
numpy.savetxt(sio, numpy.arange(10000))
s = sio.getvalue()
print s

默认输出格式为:

0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
...

并且可以用其他参数来配置它。

请特别注意,这也不会显示方括号,并允许进行大量自定义,如:how to print a Numpy array without bracket?

在Python 2.7.12,numpy 1.11.1上测试。

import numpy as np
np.set_printoptions(threshold=np.inf)

我建议使用np.inf而不是其他人建议的np.nan。它们都符合您的目的,但通过将阈值设置为“无限”,每个阅读代码的人都会明白您的意思。对我来说,“不是数字”的门槛似乎有点模糊。

这是对neoks答案的轻微修改(删除了向set_printoptions传递额外参数的选项)。

它展示了如何使用contextlib.contextmanager轻松创建这样的contextmanager,只需更少的代码行:

import numpy as np
from contextlib import contextmanager

@contextmanager
def show_complete_array():
    oldoptions = np.get_printoptions()
    np.set_printoptions(threshold=np.inf)
    try:
        yield
    finally:
        np.set_printoptions(**oldoptions)

在您的代码中,可以这样使用:

a = np.arange(1001)

print(a)      # shows the truncated array

with show_complete_array():
    print(a)  # shows the complete array

print(a)      # shows the truncated array (again)

假设您有一个numpy数组

 arr = numpy.arange(10000).reshape(250,40)

如果您想一次性打印整个数组(不切换np.set_printoptions),但想要比上下文管理器更简单(更少的代码),只需执行以下操作

for row in arr:
     print row