405

numpy.arraysたとえば、次のような方法で、formatted を印刷する方法があるかどうか、興味があります。

x = 1.23456
print '%.3f' % x

浮動小数点数を出力したい場合numpy.array、いくつかの小数が出力されます。多くの場合、「科学的」形式で出力されます。これは、低次元の配列でも読みにくいものです。ただし、numpy.array明らかに文字列として出力する必要があります%s。これに対する解決策はありますか?

4

14 に答える 14

675

set_printoptions出力の精度を設定するために使用できます。

import numpy as np
x=np.random.random(10)
print(x)
# [ 0.07837821  0.48002108  0.41274116  0.82993414  0.77610352  0.1023732
#   0.51303098  0.4617183   0.33487207  0.71162095]

np.set_printoptions(precision=3)
print(x)
# [ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]

またsuppress、小さい数に対する科学的表記法の使用を抑制します。

y=np.array([1.5e-10,1.5,1500])
print(y)
# [  1.500e-10   1.500e+00   1.500e+03]
np.set_printoptions(suppress=True)
print(y)
# [    0.      1.5  1500. ]

その他のオプションについては、set_printoptionsのドキュメントを参照してください。


NumPy 1.15.0 以降を使用して印刷オプションをローカルに適用するには、 numpy.printoptionsコンテキスト マネージャーを使用できます。たとえば、 と の内部with-suite precision=3suppress=Trueは次のように設定されています。

x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]

ただしwith-suite、印刷オプション以外はデフォルト設定に戻ります。

print(x)    
# [ 0.07334334  0.46132615  0.68935231  0.75379645  0.62424021  0.90115836
#   0.04879837  0.58207504  0.55694118  0.34768638]

以前のバージョンの NumPy を使用している場合は、コンテキスト マネージャーを自分で作成できます。例えば、

import numpy as np
import contextlib

@contextlib.contextmanager
def printoptions(*args, **kwargs):
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    try:
        yield
    finally: 
        np.set_printoptions(**original)

x = np.random.random(10)
with printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]

float の末尾からゼロが取り除かれないようにするには、次のようにします。

np.set_printoptionsには、formatter各タイプのフォーマット関数を指定できるパラメーターが追加されました。

np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)

印刷する

[ 0.078  0.480  0.413  0.830  0.776  0.102  0.513  0.462  0.335  0.712]

それ以外の

[ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]
于 2010-05-23T12:59:36.527 に答える
41

Unutbuは本当に完全な答えを出しました(彼らも私から+1を得ました)が、ここにローテクの代替手段があります:

>>> x=np.random.randn(5)
>>> x
array([ 0.25276524,  2.28334499, -1.88221637,  0.69949927,  1.0285625 ])
>>> ['{:.2f}'.format(i) for i in x]
['0.25', '2.28', '-1.88', '0.70', '1.03']

関数として (format()書式設定の構文を使用):

def ndprint(a, format_string ='{0:.2f}'):
    print [format_string.format(v,i) for i,v in enumerate(a)]

使用法:

>>> ndprint(x)
['0.25', '2.28', '-1.88', '0.70', '1.03']

>>> ndprint(x, '{:10.4e}')
['2.5277e-01', '2.2833e+00', '-1.8822e+00', '6.9950e-01', '1.0286e+00']

>>> ndprint(x, '{:.8g}')
['0.25276524', '2.283345', '-1.8822164', '0.69949927', '1.0285625']

配列のインデックスは、次の形式の文字列でアクセスできます。

>>> ndprint(x, 'Element[{1:d}]={0:.2f}')
['Element[0]=0.25', 'Element[1]=2.28', 'Element[2]=-1.88', 'Element[3]=0.70', 'Element[4]=1.03']
于 2013-08-17T10:37:56.737 に答える
17

参考までにNumpy 1.15 (リリース日保留中) には、印刷オプションをローカルに設定するためのコンテキスト マネージャーが含まれますこれは、独自のコンテキストマネージャーを作成しなくても、受け入れられた回答(unutbu および Neil G による)の対応する例と同じように、以下が機能することを意味します。たとえば、彼らの例を使用すると:

x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]
于 2018-06-18T21:46:34.783 に答える
14

結果を文字列として取得するのを非常に簡単にする宝石 (今日の派手なバージョン) は、denis answer に隠されています: np.array2string

>>> import numpy as np
>>> x=np.random.random(10)
>>> np.array2string(x, formatter={'float_kind':'{0:.3f}'.format})
'[0.599 0.847 0.513 0.155 0.844 0.753 0.920 0.797 0.427 0.420]'
于 2016-11-02T13:58:55.800 に答える
7

そして、これが私が使用するものであり、それはかなり単純です:

print(np.vectorize("%.2f".__mod__)(sparse))
于 2014-06-07T15:44:31.713 に答える
6

メソッドが言及されていないことに驚きましたaround-印刷オプションをいじらないことを意味します。

import numpy as np

x = np.random.random([5,5])
print(np.around(x,decimals=3))

Output:
[[0.475 0.239 0.183 0.991 0.171]
 [0.231 0.188 0.235 0.335 0.049]
 [0.87  0.212 0.219 0.9   0.3  ]
 [0.628 0.791 0.409 0.5   0.319]
 [0.614 0.84  0.812 0.4   0.307]]
于 2018-04-10T10:40:37.720 に答える
2

さまざまな列にさまざまな形式を持たせたいことがよくあります。これは、NumPy 配列 (のスライス) をタプルに変換することで、さまざまなフォーマットを使用して単純な 2D 配列を出力する方法です。

import numpy as np
dat = np.random.random((10,11))*100  # Array of random values between 0 and 100
print(dat)                           # Lines get truncated and are hard to read
for i in range(10):
    print((4*"%6.2f"+7*"%9.4f") % tuple(dat[i,:]))
于 2015-12-12T09:06:31.233 に答える
1

numpy.char.modアプリケーションの詳細によっては、これも役立つ場合があります。たとえばnumpy.char.mod('Value=%4.2f', numpy.arange(5, 10, 0.1))、「Value=5.00」、「Value=5.10」などの要素を含む文字列配列を返します (多少不自然な例として)。

于 2015-02-02T21:06:41.260 に答える