python 如何打印完整的NumPy數組?
6
Answers
python arrays numpy
當我打印一個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]])
294 votes
python
以前的答案是正確的,但作為一個較弱的選擇,你可以轉換成一個列表:
>>> 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]]
python1
292
Paul Price建議使用上下文管理器
import numpy as np
class fullprint:
'context manager for printing full numpy arrays'
def __init__(self, **kwargs):
if 'threshold' not in kwargs:
kwargs['threshold'] = np.nan
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)
a = np.arange(1001)
with fullprint():
print(a)
print(a)
with fullprint(threshold=None, edgeitems=10):
print(a)
python2
291
這是一個小小的修改(刪除了傳遞其他參數給set_printoptions)
的選項set_printoptions)
neok的答案。
它展示瞭如何使用contextlib.contextmanager
以較少的代碼行輕鬆創建這樣的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)
python3
290
假設你有一個numpy數組
arr = numpy.arange(10000).reshape(250,40)
如果你想以一次性的方式打印整個數組(不切換np.set_printoptions),但想要比上下文管理器更簡單(少代碼),只需要
for row in arr:
print row
python4
289
它就像python的範圍一樣 ,使用np.range(10001)
welcome!
python5
288