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
2
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

NumPy | array2string 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 array2string(~) method returns a string representation of your Numpy array formatted as specified.

This method defaults to using the configuration specified via Numpy's get_printoptions(~). You can change the default configuration using set_printoptions(~).

Parameters

1. a | array-like

The input array. Unlike most Numpy methods, a has to be a Numpy array.

2. max_line_widthlink | int | optional

The maximum number of characters per line. By default, max_line_width=75, unless overridden via set_printoptions(~).

3. precisionlink | 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 the values are uniquely differentiated. By default, precision=8 unless overridden.

4. suppress_smalllink | 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_small=False unless overridden.

5. separatorlink | string | optional

The string to separate the values. By default, separator=" " (i.e. a single whitespace).

6. prefixlink | string | optional

See the explanation of the suffix parameter below.

7. suffixlink | string | optional

Parameters prefix and suffix are used to add padding to each line. Each line can only hold a maximum of max_line_width-len(prefix)-len(suffix) characters. Note that the length of prefix and suffix matters, not their actual value since they are not printed out.

8. 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 unless overridden.

9. thresholdlink | int | optional

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

10. edgeitemslink | int | optional

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

11. 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="-" unless overridden.

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" unless overridden.

Return Value

None, since this method just prints on the screen.

Examples

Basic usage

To show 3 fractional digits:

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

To have unfixed precision, pass a None:

a = np.array([3.14, 3.1416])
np.arraystring(a, precision=None)
'[3.14 3.1416]'

Specifying max_line_width

By default, max_line_width=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:

a = np.array([12, 34, 5])
np.arraystring(a, max_line_width=7)
'[12 34\n 5]'

This is what you see when you actually print the returned string:

print(np.arraystring(a, max_line_width=7))
[12 34
5]

Specifying suppress_small

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

a = np.array([1e-5])
np.arraystring(a, suppress_small=True)
'[0.00001]'

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

a = np.array([1e-5])
np.arraystring(a)
'[1.e-05]'

Specifying separator

To override the default delimiter of a single whitespace, pass in the separator parameter:

a = np.array([3,4,5])
np.arraystring(a, separator="A")
'[3A4A5]'

Specifying suppress

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

a = np.array([1e-5])
np.arraystring(a, suppress_small=True)
'[0.00001]'

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

a = np.array([1e-5])
np.arraystring(a)
'[1.e-05]'

Specifying prefix and suffix

The length of prefix and suffix is used to add padding to each line:

a = np.arange(5)
np.arraystring(a, max_line_width=15, prefix="BB", suffix="AAA")
'[0 1 2 3\n 4]'

Here, each line is formatted as follows:

prefix + array2string(a) + suffix

Each line can only hold a maximum of 15-len(prefix)-len(suffix)=10 characters. The actual content of prefix and suffix does not matter at all since they are not printed out - only their lengths matter.

Specifying formatter

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

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

a = np.array([True, False, True])
np.arraystring(a, formatter=mapping)
[1 -1 1]

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

Specifying threshold

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

a = np.arange(1500)
np.arraystring(a)
[ 0 1 2 ... 1497 1498 1499]

This means that small arrays will not be summarised:

a = np.arange(7)
np.arraystring(a)
[0 1 2 3 4 5 6]

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

a = np.arange(7)
np.arraystring(a,threshold=3)
'[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:

a = np.arange(1500)
np.arraystring(a)
'[ 0 1 2 ... 1497 1498 1499]'

We can customise this by setting our own edgeitems:

a = np.arange(1500)
np.arraystring(a, edgeitems=4)
'[ 0 1 2 3 ... 1496 1497 1498 1499]'

Specifying sign

To show the + sign for positive numbers:

a = np.array([np.inf, 3.14, -2])
np.arraystring(a, sign="+")
'[ +inf +3.14 -2. ]'

To add a " " in front of positive numbers:

a = np.array([np.inf, 3.14, -2])
np.arraystring(a, sign=" ")
'[ inf 3.14 -2. ]'

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

Specifying floatmode

fixed

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

a = np.array([5.05, 5.05001])
np.arraystring(a, floatmode="fixed")
'[5.05000000 5.05001000]'

unique

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

a = np.array([5.05, 5.05001])
np.arraystring(a, floatmode="unique")
'[5.05 5.05001]'

Note that this ignores the precision parameter.

maxprec

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

a = np.array([5.05, 5.052999])
np.arraystring(a, floatmode="maxprec", precision=4)
'[5.05 5.053]'

maxprec_equal

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

a = np.array([5.05, 5.05001])
np.arraystring(a, floatmode="maxprec_equal")
'[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...