[PYTHON] Raise "numpy power" with [100 numpy exercises] (11th to 20th questions)

Raise "numpy power" with [100 numpy exercises](1st to 10th questions) Continuing from the previous article, I will solve the 11th to 20th questions.

  1. Create a 3x3 identity matrix (★☆☆)

** "Create a 3x3 identity matrix" **

An n × n identity matrix can be generated with np.eye (n).

100_Numpy_exercises.ipynb-(11)answer


Z = np.eye(3)
print(Z)

Execution result

100_Numpy_exercises.ipynb-(11)output


[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
  1. Create a 3x3x3 array with random values (★☆☆)

** "Create a 3x3x3 array (random elements)" **

Use the numpy.random module to generate random numbers.

100_Numpy_exercises.ipynb-(12)answer


Z = np.random.rand(3,3,3) #Random numbers in a 3x3x3 array(0.0 or more 1.Less than 0)
print(Z)

Execution result

100_Numpy_exercises.ipynb-(12)output


[[[0.44518095 0.00924118 0.59004146]
  [0.12450099 0.91674964 0.77679575]
  [0.28061072 0.03625354 0.87043565]]

 [[0.76171958 0.39143584 0.02266029]
  [0.51873782 0.60923224 0.69941338]
  [0.41821728 0.65331316 0.74005185]]

 [[0.25365995 0.45885229 0.41108347]
  [0.74013277 0.44224959 0.39538442]
  [0.27518178 0.50242514 0.54273645]]]

If you want to create an array with integer random numbers, use numpy.random.randint ().

Specify the argument in the form of numpy.random.randint (low, high, size). → Generate an array with the size specified in size with an integer random number greater than or equal to low and less than high.

100_Numpy_exercises.ipynb-(12)answer


Z = np.random.randint(1,10,(3,3,3)) #Random numbers in a 3x3x3 array(Integer greater than or equal to 1 and less than 10)
print(Z)

Execution result

100_Numpy_exercises.ipynb-(12)output


[[[4 2 8]
  [2 5 9]
  [9 4 6]]

 [[6 1 8]
  [1 6 9]
  [5 3 5]]

 [[8 9 8]
  [8 9 4]
  [7 8 4]]]
  1. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)

** "Generate a 10x10 array with random numbers and find the minimum and maximum values of the element" **

Random number generation in the first half is a review of the previous question. The problem is the second half. The minimum and maximum of array can be displayed by the functions min () and max (). It's easy to understand.

100_Numpy_exercises.ipynb-(13)answer


Z = np.random.rand(10,10)
print(Z)
print(Z.min())
print(Z.max())

Execution result

100_Numpy_exercises.ipynb-(13)output


[[0.52234883 0.04961266 0.26979588 0.35807264 0.58767559 0.66650289
  0.51751858 0.00749977 0.64916673 0.52928179]
 [0.84590062 0.475141   0.98199741 0.85117845 0.07182633 0.85569791
  0.68031337 0.39577058 0.3102539  0.05988267]
 [0.1908481  0.44464734 0.42211624 0.33883119 0.47234289 0.88443684
  0.67840264 0.11499548 0.01561011 0.62472268]
 [0.68165249 0.56003177 0.69289739 0.01834723 0.82186756 0.33528515
  0.33715765 0.89662065 0.91279419 0.95973881]
 [0.16768925 0.88251896 0.7545505  0.80567805 0.0875194  0.86998789
  0.42720398 0.73700043 0.95089544 0.87874673]
 [0.61277308 0.20511706 0.7039127  0.55107676 0.00495881 0.93791274
  0.5540698  0.17465328 0.17021889 0.75724567]
 [0.20103278 0.0402996  0.86112665 0.22460515 0.49205103 0.67606385
  0.97352361 0.48226577 0.1698369  0.75163188]
 [0.08707084 0.94483062 0.82773455 0.849915   0.54699492 0.63773099
  0.88614943 0.839312   0.2898842  0.49742767]
 [0.50516571 0.25980059 0.78911141 0.17191684 0.41938205 0.98415545
  0.22282797 0.06791284 0.44208603 0.30956802]
 [0.49319972 0.09882225 0.08468636 0.64297834 0.57264345 0.49475321
  0.0089241  0.28765751 0.84352742 0.962471  ]]
0.004958805565047131
0.9841554497271033
  1. Create a random vector of size 30 and find the mean value (★☆☆)

** "Create a vector with a size of 30 and find the average value" **

Use mean () to find the average value of array. This is also the same.

100_Numpy_exercises.ipynb-(14)answer


Z = np.random.rand(30)
print(Z)
print(Z.mean())

Execution result

100_Numpy_exercises.ipynb-(14)output


[0.71731749 0.27092985 0.47882913 0.94756227 0.35222887 0.45151348
 0.83705811 0.66280134 0.43406269 0.53061543 0.88052437 0.93703825
 0.02288098 0.4235356  0.69145184 0.97566151 0.60787705 0.15327448
 0.85466264 0.8320094  0.31804771 0.43561608 0.8271854  0.57419325
 0.83537801 0.33995759 0.92256564 0.40740555 0.70334292 0.13671002]
0.5854078986104199
  1. Create a 2d array with 1 on the border and 0 inside (★☆☆)

** "Create a two-dimensional array with a boundary of 1 and an interior of 0" **

I think there are several ways to do this, but it seems easy to create an array of all "1" s and then rewrite the inside to "0". To rewrite the inside with "0", specify the range using slices. Let's make it with a 10x10 array.

100_Numpy_exercises.ipynb-(15)answer


Z = np.ones((10,10))
Z[1:-1,1:-1]=0
print(Z)

Execution result

100_Numpy_exercises.ipynb-(15)output


array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 0., 0., 0., 1.],
       [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
  1. How to add a border (filled with 0's) around an existing array? (★☆☆)

** "How to add 0 elements around an existing array?" 』**

This is a little worrisome. Let's take a look at the hint.

hint: np.pad

It seems good to use a function called np.pad (). This pad is padding. A function that allows you to embed another element around an array.

For example, let's say you have a one-dimensional array with ʻa = [1,2,3]`. If you want to fill one before and after this array with 0s,

print(np.pad(a, [1,1], mode="constant"))

will do.

Execution result

[0, 1, 2, 3, 0]

numpy.pad(array, pad_width, mode=xxx)

array: an existing array pad_width: How many minutes before and after the array should be filled. Specify as (before_n, after_n). If the front and back are the same, you can specify it as n. mode: Which value to fill. If "constant" is specified, it will be filled with a constant (default is 0). If you want to fill it with something other than 0, specify the value N you want to fill, such as constant_values = N.

What about a two-dimensional array? let's do it.

Z = np.array([[1,2,3],
             [4,5,6]])
print(np.pad(Z, [1,1], mode="constant",constant_values=99))

Execution result

[[99 99 99 99 99]
 [99  1  2  3 99]
 [99  4  5  6 99]
 [99 99 99 99 99]]

"99" was filled around the original array.

  1. What is the result of the following expression? (★☆☆)

** "What's next? 』**

0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
np.nan in set([np.nan])
0.3 == 3 * 0.1

The result of executing each line is questioned.

First of all, what is the frequent np.nan?" Nan (also written as NaN) "means" Not a Number ", or" non-number "in Japanese. Let's say this is "a number, not a number" A symbol that represents a non-number, even though it is expected to be a number as a result of a floating-point operation.

This NaN has two major features.

** 1. No matter what value is compared (== or large or small), the result will be False **

#Compare what value with NaN(==And big and small)But the result is False
print(np.nan == 10)
print(np.nan > 10)
print(np.nan < 10)
print(np.nan == np.nan)

Execution result

False
False
False
False

** 2. No matter what value is added, subtracted, multiplied or divided, the result will be NaN **

#No matter what value is added, subtracted, multiplied or divided by NaN, the result will be NaN.
print(np.nan + 10)
print(np.nan - 10)
print(np.nan * 10)
print(np.nan / 10)

Execution result

nan
nan
nan
nan

By the way, if you type type (np.nan) and check the type of np.nan, it will be float. It's just a number, not a number. It's a little strange.

Now, based on the above, let's look at the problem line by line.

0 * np.nan

No matter what you multiply by NaN, the result is NaN. It is no exception even if it is 0.

print(0 * np.nan)

Execution result

nan

np.nan == np.nan

No matter how many you compare with NaN, it's False.

print(np.nan == np.nan)

Execution result

False

np.inf > np.nan

np.inf means "infinity". No matter how many you compare with NaN, it will be False. It is False even when compared to infinity.

print(np.inf > np.nan)

Execution result

False

np.nan - np.nan

No matter what value you add, subtract, multiply or divide with NaN, you get NaN.

print(np.nan - np.nan)

Execution result

nan

np.nan in set([np.nan])

Is there a np.nan in the set np.nan, which is True.

print(np.nan in set([np.nan]))

Execution result

True

0.3 == 3 * 0.1

This seems to be True at first glance, but the result is False.

In decimal, 0.3 is 0.3, but inside the computer, floating point numbers are represented by ** binary **. Therefore, it cannot represent exactly the same value as the decimal number 0.3.

Since it is easier to understand by actually seeing it, let's display "0.3" and "3 * 0.1" using format () to display 20 digits after the decimal point.

print(format(0.3, '.20f'))
print(format(3 * 0.1, '.20f'))

Execution result

0.29999999999999998890
0.30000000000000004441

You can see that neither is exactly 0.3.

Therefore, "0.3" and "3 * 0.1" are not equivalent, so 0.3 == 3 * 0.1 is False.

print(0.3 == 3 * 0.1)

Execution result

False
  1. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) ** "Create a 5x5 array with 1,2,3,4 components just below the diagonal component" **

It's hard to understand, but I wonder if I should make an array like this. numpy_100_18.png

Use np.diag () to work with the diagonal elements of the array.

If you specify a vector or list as an argument, a square matrix with that as the diagonal component is created.

print(np.diag([1,2,3,4]))

Execution result

[[1 0 0 0]
 [0 2 0 0]
 [0 0 3 0]
 [0 0 0 4]]

You can specify another parameter called k in np.diag ().

For example, np.diag (v, k = n) will generate an array in which n elements above the diagonal component are v. (If n is a negative number, the element n below the diagonal component is v)

The problem this time is not the diagonal component, but the element immediately below the diagonal component is 1,2,3,4, so Specify k = -1 in the argument of np.diag ().

100_Numpy_exercises.ipynb-(18)answer


Z = np.diag([1,2,3,4],k=-1)
print(Z)

Execution result

100_Numpy_exercises.ipynb-(18)output


[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]
  1. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) ** "Create an array of 8x8 checkerboard patterns" **

The checkerboard pattern is such a pattern. It's also called a checkered pattern.

numpy_100_19_checker.png

The white color of this pattern is "0" and the black color is "1", and the following arrangement can be created.

numpy_100_19.png

First, create an 8x8 array with all 0 elements, and then rewrite every other element to 1.

100_Numpy_exercises.ipynb-(19)answer


Z = np.zeros((8,8),dtype=int)
Z[::2,::2] = 1
Z[1::2,1::2] = 1
print(Z)

Execution result

100_Numpy_exercises.ipynb-(19)output


[[1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]
 [1 0 1 0 1 0 1 0]
 [0 1 0 1 0 1 0 1]]
  1. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? ** "What is the index (x, y, z) of the 100th element in a 6x7x8 multidimensional array? 』**

For the sake of simplicity, we will use a 3x3 matrix. numpy_100_20.png

Multidimensional arrays can also be arranged in one dimension and indexed from the head. At that time, for example, the fifth element (index is ** 4 **) in the above figure is expressed as ** (1,1) ** when expressed by the index of a 3 × 3 two-dimensional array. can do.

You can think of np.unravel_index () as a function that converts an index expressed in one dimension into an index in a multidimensional array.

np.unravel_index(indices,shape)

The argument indices is a one-dimensional index. shape specifies the size of the multidimensional array.

This time, I want to express the index of the 100th element as an index in a 6x7x8 multidimensional array, so I can write it as follows. (Because it is 100th, the index will be 99)

100_Numpy_exercises.ipynb-(20)answer


print(np.unravel_index(99, (6,7,8)))

Execution result

100_Numpy_exercises.ipynb-(20)output


(1, 5, 3)

That's all for this time. I have a crunchy problem. Next time, I will solve the 21st to 30th questions.

Recommended Posts

Raise "numpy power" with [100 numpy exercises] (11th to 20th questions)
Raise "numpy power" with [100 numpy exercises] (11th to 20th questions)
How to power off Linux with Ultra96-V2
Add rows to an empty array with numpy
How to power off Linux with Ultra96-V2
Add rows to an empty array with numpy