how to use the numpy string formatter to print a numpy array where the output string is dependent on the array value?

  • Last Update :
  • Techknowledgy :

If you want to make sure, every element of the array is definitely printed with your formatter, use all:

import numpy as np

arr = np.zeros((2, 2))
arr[(0, 0)] = 1
arr[(0, 1)] = 2
printValues = {
   0: 'a',
   1: 'b',
   2: 'c'
}
print(np.array2string(arr, formatter = {
   'all': lambda x: printValues[int(x)]
}))

IIUC vectorize

np.vectorize(printValues.get)(arr)
array([
   ['b', 'c'],
   ['a', 'a']
], dtype = '<U1')

Suggestion : 2

I want to print a string depending on the anycodings_numpy values in a NumPy array, e.g. value 0 should anycodings_numpy lead to letter 'a'.,If you want to make sure, every element anycodings_numpy of the array is definitely printed with anycodings_numpy your formatter, use all:,The keyword argument formatter for anycodings_numpy array2string needs the type of the anycodings_numpy elements of the array which you want to anycodings_numpy replace, not the type which you're anycodings_numpy converting to.,See the above linked documentation for anycodings_numpy more available types. Maybe float_kind anycodings_numpy is also a good idea for you.

I want to print a string depending on the anycodings_numpy values in a NumPy array, e.g. value 0 should anycodings_numpy lead to letter 'a'.

import numpy as np

arr = np.zeros((2, 2))
arr[(0, 0)] = 1
arr[(0, 1)] = 2
printValues = {
   0: 'a',
   1: 'b',
   2: 'c'
}
print(np.array2string(arr, formatter = {
   'str': lambda x: printValues[x]
}))

Expected result:

[
   ['b'
      'c'
   ]
   ['a'
      'a'
   ]
]

Observed:

[
   [1. 2.]
   [0. 0.]
]

If you want to make sure, every element anycodings_numpy of the array is definitely printed with anycodings_numpy your formatter, use all:

import numpy as np

arr = np.zeros((2, 2))
arr[(0, 0)] = 1
arr[(0, 1)] = 2
printValues = {
   0: 'a',
   1: 'b',
   2: 'c'
}
print(np.array2string(arr, formatter = {
   'all': lambda x: printValues[int(x)]
}))

IIUC vectorize

np.vectorize(printValues.get)(arr)
array([
   ['b', 'c'],
   ['a', 'a']
], dtype = '<U1')

Suggestion : 3

The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as:,The output is left-padded by the length of the prefix string, and wrapping is forced at the column max_line_width - len(suffix). It should be noted that the content of prefix and suffix strings are not included in the output.,This is a very flexible function; array_repr and array_str are using array2string internally so keywords with the same name should work identically in all three functions.,If set to the string ‘1.13’ enables 1.13 legacy printing mode. This approximates numpy 1.13 print output by including a space in the sign position of floats and different behavior for 0d arrays. If set to False, disables legacy mode. Unrecognized strings will be ignored with a warning for forward compatibility.

prefix + array2string(a) + suffix
>>> x = np.array([1e-16, 1, 2, 3]) >>>
   np.array2string(x, precision = 2, separator = ',',
      ...suppress_small = True)
'[0.,1.,2.,3.]'
>>> x = np.arange(3.) >>>
   np.array2string(x, formatter = {
      'float_kind': lambda x: "%.2f" % x
   })
'[0.00 1.00 2.00]'
>>> x = np.arange(3) >>>
   np.array2string(x, formatter = {
      'int': lambda x: hex(x)
   })
'[0x0 0x1 0x2]'

Suggestion : 4

The easiest way to create an array is to use the array function. This accepts any sequence-like object (including other arrays) and produces a new NumPy array containing the passed data. For example, a list is a good candidate for conversion:,Whenever you see “array”, “NumPy array”, or “ndarray” in the text, with few exceptions they all refer to the same thing: the ndarray object.,NumPy array indexing is a rich topic, as there are many ways you may want to select a subset of your data or individual elements. One-dimensional arrays are simple; on the surface they act similarly to Python lists:,As a simple example, suppose we wished to evaluate the function sqrt(x^2 + y^2) across a regular grid of values. The np.meshgrid function takes two 1D arrays and produces two 2D matrices corresponding to all pairs of (x, y) in the two arrays:

In[13]: data1 = [6, 7.5, 8, 0, 1]

In[14]: arr1 = np.array(data1)

In[15]: arr1
Out[15]: array([6., 7.5, 8., 0., 1.])
In[27]: arr1 = np.array([1, 2, 3], dtype = np.float64)

In[28]: arr2 = np.array([1, 2, 3], dtype = np.int32)

In[29]: arr1.dtype In[30]: arr2.dtype
Out[29]: dtype('float64') Out[30]: dtype('int32')
In[45]: arr = np.array([
   [1., 2., 3.],
   [4., 5., 6.]
])

In[46]: arr
Out[46]:
   array([
      [1., 2., 3.],
      [4., 5., 6.]
   ])

In[47]: arr * arr In[48]: arr - arr
Out[47]: Out[48]:
   array([
      [1., 4., 9.], array([
         [0., 0., 0.],
         [16., 25., 36.]
      ])[0., 0., 0.]
   ])
In[51]: arr = np.arange(10)

In[52]: arr
Out[52]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In[53]: arr[5]
Out[53]: 5

In[54]: arr[5: 8]
Out[54]: array([5, 6, 7])

In[55]: arr[5: 8] = 12

In[56]: arr
Out[56]: array([0, 1, 2, 3, 4, 12, 12, 12, 8, 9])
In[75]: arr[1: 6]
Out[75]: array([1, 2, 3, 4, 64])
In[83]: names = np.array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])

In[84]: data = np.random.randn(7, 4)

In[85]: names
Out[85]:
   array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'],
      dtype = '|S4')

In[86]: data
Out[86]:
   array([
      [-0.048, 0.5433, -0.2349, 1.2792],
      [-0.268, 0.5465, 0.0939, -2.0445],
      [-0.047, -2.026, 0.7719, 0.3103],
      [2.1452, 0.8799, -0.0523, 0.0672],
      [-1.0023, -0.1698, 1.1503, 1.7289],
      [0.1913, 0.4544, 0.4519, 0.5535],
      [0.5994, 0.8174, -0.9297, -1.2564]
   ])

Suggestion : 5

We can easily calculate the entire array of of velocities using the slicing and vectorized subtraction properties of NumPy arrays by noting that we can create two y arrays displaced by one index,NumPy has a number of functions for creating arrays. We focus on four (or five or six, depending on how you count!). The first of these, the array function, converts a list to an array:,There are a number of other functions for creating arrays. For example, a 3 row by 4 column array or array with all the elements filled with 1 can be created using the ones function introduced earlier.,In other languages, data types similar to Python dictionaries may be called “hashmaps” or “associative arrays”, so you may see such term used if you read on the web about dictionaries.

In[1]: a = "My dog's name is"
In[2]: b = "Bingo"
In[3]: c = a + " " + b
In[4]: c
Out[4]: "My dog's name is Bingo"
In[5]: d = "927"
In[6]: e = 927
In[1]: a = [0, 1, 1, 2, 3, 5, 8, 13]
In[2]: b = [5., "girl", 2 + 0 j, "horse", 21]
In[3]: b[0]
Out[3]: 5.0

In[4]: b[1]
Out[4]: 'girl'

In[5]: b[2]
Out[5]: (2 + 0 j)
In[6]: b[4]
Out[6]: 21

In[7]: b[-1]
Out[7]: 21

In[8]: b[-2]
Out[8]: 'horse'