search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
chevron_leftDocumentation
Method argpartition
NumPy Random Generator4 topics
Method choiceMethod dotMethod finfoMethod histogramMethod iinfoMethod maxMethod meanMethod placeMethod rootsMethod seedMethod uniformMethod viewMethod zerosMethod sumObject busdaycalendarMethod is_busdayProperty dtypeMethod uniqueMethod loadtxtMethod vsplitMethod fliplrMethod setdiff1dMethod msortMethod argsortMethod lexsortMethod aroundMethod nanmaxMethod nanminMethod nanargmaxMethod nanargminMethod argmaxMethod argminProperty itemsizeMethod spacingMethod fixMethod ceilMethod diffProperty flatProperty realProperty baseMethod flipMethod deleteMethod amaxMethod aminMethod logical_xorMethod logical_orMethod logical_notMethod logical_andMethod logaddexpMethod logaddexp2Method logspaceMethod not_equalMethod equalMethod greater_equalMethod lessMethod less_equalMethod remainderMethod modMethod emptyMethod greaterMethod isfiniteMethod busday_countMethod repeatMethod varMethod random_sampleMethod randomMethod signMethod stdMethod absoluteMethod absMethod sortMethod randintMethod isrealMethod linspaceMethod gradientMethod allMethod sampleProperty TProperty imagMethod covMethod insertMethod logMethod log1pMethod exp2Method expm1Method expMethod arccosMethod cosMethod arcsinMethod sinMethod tanMethod fromiterMethod trim_zerosMethod diagflatMethod savetxtMethod count_nonzeroProperty sizeProperty shapeMethod reshapeMethod resizeMethod triuMethod trilMethod eyeMethod arangeMethod fill_diagonalMethod tileMethod saveMethod transposeMethod swapaxesMethod meshgridProperty mgridMethod rot90Method log2Method radiansMethod deg2radMethod rad2degMethod degreesMethod log10Method appendMethod cumprodProperty nbytesMethod tostringProperty dataMethod modfMethod fmodMethod tolistMethod datetime_as_stringMethod datetime_dataMethod array_splitMethod itemsetMethod floorMethod put_along_axisMethod cumsumMethod bincountMethod putMethod putmaskMethod takeMethod hypotMethod sqrtMethod squareMethod floor_divideMethod triMethod signbitMethod flattenMethod ravelMethod rollMethod isrealobjMethod diagMethod diagonalMethod quantileMethod onesMethod iscomplexobjMethod iscomplexMethod isscalarMethod divmodMethod isnatMethod percentileMethod isnanMethod divideMethod addMethod reciprocalMethod positiveMethod subtractMethod medianMethod isneginfMethod isposinfMethod float_powerMethod powerMethod negativeMethod maximumMethod averageMethod isinfMethod multiplyMethod busday_offsetMethod identityMethod interpMethod squeezeMethod get_printoptionsMethod savez_compressedMethod savezMethod loadMethod asfarrayMethod clipMethod arrayMethod array_equivMethod array_equalMethod frombufferMethod set_string_functionMethod matmulMethod genfromtxtMethod fromfunctionMethod asscalarMethod searchsortedMethod full_likeMethod fullMethod shares_memoryMethod ptpMethod digitizeMethod argwhereMethod geomspaceMethod zeros_likeMethod fabsMethod flatnonzeroMethod vstackMethod dstackMethod fromstringMethod tobytesMethod expand_dimsMethod ranfMethod arctanMethod itemMethod extractMethod compressMethod chooseMethod asarrayMethod asmatrixMethod allcloseMethod iscloseMethod anyMethod corrcoefMethod truncMethod prodMethod crossMethod true_divideMethod hsplitMethod splitMethod rintMethod ediff1dMethod lcmMethod gcdMethod cbrtMethod flipudProperty ndimMethod array2stringMethod set_printoptionsMethod whereMethod hstack
Char32 topics
check_circle
Mark as learned
thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

NumPy | set_printoptions method

schedule Aug 12, 2023
Last updated
local_offer
PythonNumPy
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Numpy's set_printoptions(~) method customizes how Numpy arrays are printed.

Parameters

1. precision | int or None | optional

The number of decimal places to show. A precision of 3 would mean 3.1415 becomes 3.142. If None is passed and floatmode is not fixed, then the precision will be such that they values are uniquely differentiated. By default, precision=8.

2. thresholdlink | int | optional

If the number of values in the array is larger than threshold, then instead of printing each and every values, the values will be truncated with .... By default, threshold=1000.

3. edgeitemslink | int | optional

If truncation occurs, then the number of values to show in the front and back. By default, edgeitems=3.

4. linewidthlink | int | optional

The number of characters per line. By default, linewidth=75.

5. suppresslink | boolean | optional

Whether to show values in full decimals instead of using scientific notation. This is only applicable for floats whose absolute values are smaller than 1e-4, or the ratio between the largest value and the smallest value in the array is larger than 1000. By default, suppress=False.

6. nanstrlink | string | optional

The string to replace any nan in the array. By default, the nanstr="nan".

7. infstrlink | string | optional

The string to replace any inf in the array. By default, infstr="inf".

8. signlink | string | optional

How to handle the sign of the values:

Value

Description

"-"

Omits the +.

"+"

Places a + in front of positive numbers.

" "

Places a single white space in front of positive numbers.

By default, sign="-".

9. formatterlink | dict<string,function> | optional

The mapping to apply to different data-types. The dictionary's key-value pair is as follows:

  • key: the type you wish to apply a mapping on

  • value: a function that takes as input the value with type key, and returns a new value.

Here are some of main data-types:

Type

Description

"bool"

Convert booleans.

"int"

Convert integers.

"float"

Convert floats.

"timedelta"

Convert timedeltas.

"datatime"

Convert datetimes.

Here are some special keys that you can provide:

Key

Description

"all"

Convert all data-types.

"float_kind"

Convert "float" and "longfloat"

"str_kind"

Convert "str" and "numpystr"

By default, formatter=None.

10. floatmodelink | string | optional

How to handle precision for floats:

Value

Description

"fixed"

Always show the specified precision. This results in all floats having the same decimal place.

"unique"

Show minimum number of decimal places so as to uniquely identify the values. This ignores the specified precision.

"maxprec"

Prints at most the specified precision.

"maxprec_equal"

Prints at most the specified precision, and also ensures that all floats have the same decimal place.

By default, floatmode="maxprec_equal".

Return value

None, since this method just prints on the screen.

Examples

Basic usage

To show 3 fractional digits:

np.set_printoptions(precision=3)
np.array([0.000005, 3.1416])
array([5.000e-06, 3.142e+00])

To have unfixed precision, pass a None:

np.set_printoptions(precision=None)
np.array([3.14, 3.1416])
array([3.14 , 3.142])

Specifying threshold

By default, threshold=1000, which means that printing arrays that have 1000 values or more will be summarised:

print(np.arange(1500))
[ 0 1 2 ... 1497 1498 1499]

This means that small arrays will not be summarised:

print(np.arange(7))
[0 1 2 3 4 5 6]

We can set a threshold so that even these small arrays will be summarised:

np.set_printoptions(threshold=3)
np.arange(7)
array([0, 1, 2, ..., 4, 5, 6])

Specifying edgeitems

By default, edgeitems=3, which means that when values are summarised, 3 values will be shown on the left, and 3 on the right:

print(np.arange(1500))
[ 0 1 2 ... 1497 1498 1499]

We can customise this by setting our own edgeitems:

np.set_printoptions(edgeitems=4)
print(np.arange(1500))
[ 0 1 2 3 ... 1496 1497 1498 1499]

Specifying linewidth

By default, linewidth=75, which means that each printed line can have at most 75 characters:

print(np.array([12, 34, 5]))
[12 34 5]

To print at most only 7 characters per line:

np.set_printoptions(linewidth=7)
print(np.array([12, 34, 5]))
[12 34
5]

Specifying suppress

To show all decimal places for numbers smaller than 1e-4:

np.set_printoptions(suppress=True)
print(np.array([1e-5]))
[0.00001]

The default behaviour of suppress=False gives us the following:

np.set_printoptions(suppress=False)
print(np.array([1e-5]))
[1.e-05]

Specifying nanstr

np.set_printoptions(nanstr="Missing!")
print(np.array([np.NaN, 3.14]))
[Missing! 3.14]

Specifying infstr

np.set_printoptions(infstr="Infinity!")
print(np.array([np.inf, 3.14]))
[Infinity! 3.14]

Specifying sign

To show the + sign for positive numbers:

np.set_printoptions(sign="+")
print(np.array([np.inf, 3.14, -2]))
[ +inf +3.14 -2. ]

To add a " " in front of positive numbers:

np.set_printoptions(sign=" ")
print(np.array([np.inf, 3.14, -2]))
[ inf 3.14 -2. ]

It's hard to see here, but a single whitespace has been added.

Specifying formatter

To convert all boolean True to 1 and False to "-1".

mapping = {
"bool": lambda x: "1" if x else "-1"
}

np.set_printoptions(formatter=mapping)
print(np.array([True, False, True]))
[1 -1 1]

Here, make sure you return a string in the mapping, otherwise an error will be thrown.

Specifying floatmode

fixed

To print floats with the same decimal places (i.e. 8 by default):

np.set_printoptions(floatmode="fixed")
print(np.array([5.05, 5.05001]))
[5.05000000 5.05001000]

unique

To print floats with the minimum number of decimal places so as to uniquely identify the values:

np.set_printoptions(floatmode="unique")
print(np.array([5.05, 5.05001]))
[5.05 5.05001]

Note that this ignores the precision parameter.

maxprec

Same as unique, but the floats can have at most precision:

np.set_printoptions(floatmode="maxprec", precision=4)
print(np.array([5.05, 5.052999]))
[5.05 5.053]

maxprec_equal

Same as maxprec, but the floats will all have the same precision:

np.set_printoptions(floatmode="maxprec_equal")
print(np.array([5.05, 5.05001]))
[5.05000 5.05001]
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...