添加到尼克T的答案:
您可以編輯numpy的打印選項,所以每當您打印一個numpy陣列格式化將發生。
In [191]: np.set_printoptions(formatter={'all':lambda x: '{:+}'.format(x)})
In [198]: np.random.random_integers(-5,5,(5,5))
Out[198]:
array([[+2, +2, +2, -4, +0],
[-2, -1, +3, +5, -1],
[-5, -2, -1, -3, +4],
[+1, +3, -5, +3, -4],
[+2, -1, +2, +5, +5]])
的'all'
定義該格式應該使用什麼類型。 set_printoptions的文檔字符串將告訴您可以在那裏設置更具體的格式。
- 'bool'
- 'int'
- 'timedelta' : a `numpy.timedelta64`
- 'datetime' : a `numpy.datetime64`
- 'float'
- 'longfloat' : 128-bit floats
- 'complexfloat'
- 'longcomplexfloat' : composed of two 128-bit floats
- 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
- 'str' : all other strings
Other keys that can be used to set a group of types at once are::
- 'all' : sets all types
- 'int_kind' : sets 'int'
- 'float_kind' : sets 'float' and 'longfloat'
- 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
- 'str_kind' : sets 'str' and 'numpystr'
非常感謝你!但是當我嘗試,我得到這個錯誤:ValueError:簽名不允許在字符串格式說明符。如果我嘗試將我的數組變量作爲整數進行投射,它根本就不會做任何事情。我想這是因爲我正在從文件中讀取這些值,它認爲這些值是字符串?或者可能是因爲「+」和「 - 」在我的輸入中? – FairyDuster
是的,你可能有dtypes作爲字符串。所以你需要轉換數組的dtype。這應該這樣做:'a = a.astype(int)',或者你可以在創建數組時設置dtype。 – M4rtini
工作!非常感謝! :)))) – FairyDuster