【问题标题】:How to print the full NumPy array, without truncation?如何在不截断的情况下打印完整的 NumPy 数组?
【发布时间】:2019-10-06 13:16:18
【问题描述】:

当我打印一个 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]])

【问题讨论】:

  • 有没有办法在“一次性”的基础上做到这一点?也就是说,在脚本中打印一次完整的输出,而不是其他时间?
  • @Matt O'Brien 请参阅下面 ZSG 的回答
  • 您能否将接受的答案更改为推荐np.inf 的答案? np.nan 和 'nan' 只能通过侥幸实现,而 'nan' doesn't even work in Python 3 因为他们改变了 threshold='nan' 所依赖的混合类型比较实现。
  • (threshold=np.nan 而不是'nan' 取决于不同的侥幸,即数组打印逻辑将数组大小与a.size > _summaryThreshold 的阈值进行比较。这总是返回False for @ 987654333@。如果比较的是a.size <= _summaryThreshold,则测试是否应该完全打印数组而不是测试是否应该汇总,此阈值将触发所有数组的汇总。)
  • 一种“一次性”的方式:如果你有一个 numpy.array tmp 只是 list(tmp)。其他具有不同格式的选项是tmp.tolist() 或更多控制print("\n".join(str(x) for x in tmp))。

标签: python arrays numpy options output-formatting


【解决方案1】:

这听起来像是你在使用 numpy。

如果是这样,您可以添加:

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

这将禁用角落打印。有关详细信息,请参阅此NumPy Tutorial。

【讨论】:

  • ValueError: threshold must be numeric and non-NAN, try sys.maxsize for untruncated representation
  • 是的,Numpy官方教程的那部分是错误的
【解决方案2】:

使用numpy.set_printoptions:

import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)

【讨论】:

  • 如果您只想打印一次 numpy 数组,不幸的是,此解决方案的缺点是要求您在打印后重置​​此配置更改。
  • @TrevorBoydSmith,你知道打印后如何重置这个参数吗?
  • @ColinMac 请参阅stackoverflow.com/a/24542498/52074 他保存设置的位置。做一个手术。然后恢复设置。
  • 如何恢复正常?
  • @Gulzar 使用:numpy.set_printoptions(threshold = False)
【解决方案3】:

这是一种一次性的方法,如果您不想更改默认设置,这很有用:

def fullprint(*args, **kwargs):
  from pprint import pprint
  import numpy
  opt = numpy.get_printoptions()
  numpy.set_printoptions(threshold=numpy.inf)
  pprint(*args, **kwargs)
  numpy.set_printoptions(**opt)

【讨论】:

  • 看起来这是一个使用上下文管理器的好地方,所以你可以说“with fullprint”。
【解决方案4】:
import numpy as np
np.set_printoptions(threshold=np.inf)

我建议使用np.inf 而不是其他人建议的np.nan。它们都为您的目的而工作,但是通过将阈值设置为“无穷大”,每个阅读您的代码的人都清楚您的意思。有一个“不是数字”的阈值对我来说似乎有点模糊。

【讨论】:

  • 这个的逆运算是什么?如何回到之前的设置(带点)?
  • @Karlo 默认数字是 1000,所以np.set_printoptions(threshold=1000) 会将其恢复为默认行为。但是您可以根据需要将此阈值设置为低或高。 np.set_printoptions(threshold=np.inf) 只是更改打印数组在被截断为无限之前的最大大小,因此无论它有多大都不会被截断。如果您将阈值设置为任何实数,那么这将是最大大小。
  • 这不仅更清晰,而且不那么脆弱。 np.inf、np.nan 或 'nan'没有特殊处理。不管你放什么,NumPy 仍然会使用一个普通的> 来比较数组的大小和你的阈值。 np.nan 恰好起作用,因为它是a.size > _summaryThreshold 而不是a.size <= _summaryThreshold,并且np.nan 为所有>/</>=/<= 比较返回False。 'nan' 只是由于 Python 2 的混合类型比较逻辑的脆弱实现细节而发生工作;它在 Python 3 上完全崩溃了。
  • 使用 sys.maxsize 因为该值被记录为 int
  • 要正确回答@Karlo 的问题,请注意打印选项阈值的初始值位于np.get_printoptions()['threshold']。您可以在设置阈值之前存储此值,然后再将其恢复(或按照其他答案中的建议使用 with 块)。
【解决方案5】:

前面的答案是正确的,但作为较弱的选择,您可以转换为列表:

>>> numpy.arange(100).reshape(25,4).tolist()

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21,
22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35], [36, 37, 38, 39], [40, 41,
42, 43], [44, 45, 46, 47], [48, 49, 50, 51], [52, 53, 54, 55], [56, 57, 58, 59], [60, 61,
62, 63], [64, 65, 66, 67], [68, 69, 70, 71], [72, 73, 74, 75], [76, 77, 78, 79], [80, 81,
82, 83], [84, 85, 86, 87], [88, 89, 90, 91], [92, 93, 94, 95], [96, 97, 98, 99]]

【讨论】:

  • 这似乎是在打印语句中查看完整数组的最佳一次性方式。
  • @AaronBramson 我同意...当您只需要一个打印语句(一行代码而不是 3 行代码:更改配置、打印、重置配置)时,这不太容易出错。
  • 我喜欢这样打印逗号分隔符
  • 这个解决方案非常适合整数,但不太适合双精度数
【解决方案6】:

建议使用上下文管理器作为Paul Price

import numpy as np


class fullprint:
    'context manager for printing full numpy arrays'

    def __init__(self, **kwargs):
        kwargs.setdefault('threshold', np.inf)
        self.opt = kwargs

    def __enter__(self):
        self._opt = np.get_printoptions()
        np.set_printoptions(**self.opt)

    def __exit__(self, type, value, traceback):
        np.set_printoptions(**self._opt)


if __name__ == '__main__': 
    a = np.arange(1001)

    with fullprint():
        print(a)

    print(a)

    with fullprint(threshold=None, edgeitems=10):
        print(a)

【讨论】:

【解决方案7】:

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 brackets?中所述

在 Python 2.7.12、numpy 1.11.1 上测试。

【讨论】:

  • 这种方法的小缺点是只适用于一维和二维数组
  • @Fnord 感谢您提供此信息,如果您找到解决方法,请告诉我!
【解决方案8】:

如果数组太大而无法打印,NumPy 会自动跳过数组的中心部分,只打印角落: 要禁用此行为并强制 NumPy 打印整个数组,您可以使用 set_printoptions 更改打印选项。

>>> np.set_printoptions(threshold='nan')

或

>>> np.set_printoptions(edgeitems=3,infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)

您也可以参考numpy documentationnumpy documentation for "or part"获取更多帮助。

【讨论】:

  • 请勿使用'nan'、np.nan 或以上任何一种。它不受支持,这个糟糕的建议给过渡到 python 3 的人带来了痛苦
  • ValueError: threshold must be numeric and non-NAN, try sys.maxsize for untruncated representation
【解决方案9】:

这是一个微小的修改(删除了将附加参数传递给set_printoptions)of neoks 答案的选项。

它展示了如何使用contextlib.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)

【讨论】:

  • 您应该始终在上下文管理器中将try / finally 放在yield 周围,以便无论如何都会进行清理。
  • @Eric 确实如此。感谢您的有用评论,我已经更新了答案。
  • 在 1.15 中,可以拼写成with np.printoptions(threshold=np.inf):
【解决方案10】:

假设你有一个 numpy 数组

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

如果您想以一次性方式打印整个数组(无需切换 np.set_printoptions),但想要比上下文管理器更简单(代码更少)的东西,只需这样做

for row in arr:
     print row 

【讨论】:

    【解决方案11】:

    您可以使用array2string 函数 - docs。

    a = numpy.arange(10000).reshape(250,40)
    print(numpy.array2string(a, threshold=numpy.nan, max_line_width=numpy.nan))
    # [Big output]
    

    【讨论】:

    • ValueError: threshold must be numeric and non-NAN, try sys.maxsize for untruncated representation
    【解决方案12】:

    与此answer 的最大列数(用numpy.set_printoptions(threshold=numpy.nan) 固定)互补,还有要显示的字符限制。在某些环境中,例如从 bash(而不是交互式会话)调用 python 时,可以通过如下设置参数 linewidth 来解决此问题。

    import numpy as np
    np.set_printoptions(linewidth=2000)    # default = 75
    Mat = np.arange(20000,20150).reshape(2,75)    # 150 elements (75 columns)
    print(Mat)
    

    在这种情况下,您的窗口应该限制换行的字符数。

    对于那些使用 sublime 文本并希望在输出窗口中查看结果的人,您应该将构建选项 "word_wrap": false 添加到 sublime-build 文件 [source] 中。

    【讨论】:

      【解决方案13】:

      临时设置

      如果您使用 NumPy 1.15(2018-07-23 发布)或更新版本,您可以使用 printoptions 上下文管理器:

      with numpy.printoptions(threshold=numpy.inf):
          print(arr)
      

      (当然,如果您是这样导入 numpy,请将 numpy 替换为 np)

      使用上下文管理器(with-block)确保在上下文管理器完成后,打印选项将恢复到块开始之前的状态。它确保设置是临时的,并且仅应用于块内的代码。

      有关上下文管理器及其支持的其他参数的详细信息,请参阅numpy.printoptions documentation。

      【讨论】:

      • 为 numpy 导入别名的人的快捷方式:with np.printoptions(threshold=np.inf):
      • @zr0gravity7 这已经写在我的答案中,就在示例下方。
      【解决方案14】:

      自 NumPy 1.16 版起,更多详情请参阅GitHub ticket 12251。

      from sys import maxsize
      from numpy import set_printoptions
      
      set_printoptions(threshold=maxsize)
      

      【讨论】:

        【解决方案15】:

        您不会总是希望打印所有项目,尤其是对于大型阵列。

        显示更多项目的简单方法:

        In [349]: ar
        Out[349]: array([1, 1, 1, ..., 0, 0, 0])
        
        In [350]: ar[:100]
        Out[350]:
        array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1,
               1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
               0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
               0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1])
        

        默认切片数组

        【讨论】:

          【解决方案16】:

          关闭它并返回正常模式

          np.set_printoptions(threshold=False)
          

          【讨论】:

          • 它适用于我(Jupyter python 版本 3)。您可以尝试下面的代码。根据官方文档,下面的代码应该恢复默认选项。它也为我做了。 >np.set_printoptions(edgeitems=3,infstr='inf', linewidth=75, nanstr='nan', precision=8, suppress=False, threshold=1000, formatter=None)
          • 好吧,一定是因为我没有使用 Jupyter。不过,接受的答案在纯 python 环境中对我有用。
          • 这表示threshold=0,意思是“尽快截断”——这根本不是你想要的。
          【解决方案17】:

          稍作修改:(因为您要打印一个巨大的列表)

          import numpy as np
          np.set_printoptions(threshold=np.inf, linewidth=200)
          
          x = np.arange(1000)
          print(x)
          

          这将增加每行的字符数(默认线宽为 75)。为适合您的编码环境的线宽使用您喜欢的任何值。这将使您不必通过每行添加更多字符来处理大量输出行。

          【讨论】:

            【解决方案18】:

            如果你有熊猫,

                numpy.arange(10000).reshape(250,40)
                print(pandas.DataFrame(a).to_string(header=False, index=False))
            

            避免了需要重置numpy.set_printoptions(threshold=sys.maxsize) 的副作用,并且您不会得到 numpy.array 和括号。我发现这很方便将宽数组转储到日志文件中

            【讨论】:

              【解决方案19】:

              如果您使用的是 Jupyter,请尝试使用 variable inspector 扩展名。您可以单击每个变量来查看整个数组。

              【讨论】:

                【解决方案20】:

                如果您使用的是 jupyter 笔记本,我发现这是一次性情况下最简单的解决方案。基本上将numpy数组转换为列表,然后转换为字符串,然后打印。这样做的好处是将逗号分隔符保留在数组中,而使用 numpyp.printoptions(threshold=np.inf) 则不会:

                import numpy as np
                print(str(np.arange(10000).reshape(250,40).tolist()))
                

                【讨论】:

                  【解决方案21】:
                  with np.printoptions(edgeitems=50):
                      print(x)
                  

                  将 50 改为你想看的行数

                  来源:here

                  【讨论】:

                    猜你喜欢
                    • 2019-08-23
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-08-21
                    • 2020-05-16
                    相关资源
                    最近更新 更多