[PYTHON] numpy part 2

python


import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)
print(arr.shape)
print(arr.ndim)

print('###############')

arr2 = np.array([1, 2, 3, 4 ,5 ,6])

print(arr2)
print(arr2.shape)
print(arr.ndim)

print('###############')

arr3 = arr2.reshape(3, 2)

print(arr3)
print(arr3.shape)
print(arr3.ndim)

print('###############')

arr3 = arr2.reshape(3, -1)

print(arr3)
print(arr3.shape)
print(arr3.ndim)

Execution result


[[1 2 3]
 [4 5 6]]
(2, 3)
2
###############
[1 2 3 4 5 6]
(6,)
2
###############
[[1 2]
 [3 4]
 [5 6]]
(3, 2)
2
###############
[[1 2]
 [3 4]
 [5 6]]
(3, 2)
2

You can get the shape in the form of (row, column) with shpe. You can use ndim to get the number of dimensions of a multidimensional array.

Use the reshape () method to change the shape. Specify the shape in the form of (row, column) in the argument of reshape ().

The array after changing the shape with reshape and the original array must have the same number of elements. In the above example, the array arr2 has 6 elements. It can be reshaped with arr.reshape ((2, 3)). (Because 2 x 3 = 6) If the number of elements is different, ValueError will occur.

By passing 3 and -1 as the argument of reshape, a 3x2 array is automatically generated.

Recommended Posts

numpy part 1
numpy part 2
datetime part 1
Numpy [Basic]
argparse part 1
numpy tips
Multidimensional array calculation without Numpy Part 2
About numpy
NumPy axis
Use Numpy
Queuing theory part 4
neo4j sandbox part 12
QGIS + Python Part 2
neo4j sandbox part 5
Django begins part 1
Manim's method part 23
Report_Deep Learning (Part 1)
Report_Deep Learning (Part 1)
QGIS + Python Part 1
GMT installation part 2.
GMT installation part 1.
Django begins part 4
numpy unit test
NumPy array manipulation (3)
Report_Deep Learning (Part 2)
list and numpy
neo4j sandbox part 13
NumPy universal functions
neo4j sandbox part 15
numpy memorandum 1 / np.pad
#Python basics (#Numpy 1/2)
#Python basics (#Numpy 2/2)
numpy index search
Python: Scraping Part 1
NumPy array manipulation (1)
neo4j sandbox part 16
Python #Numpy basics
numpy non-basic techniques
About Numpy broadcast
[PyTorch] Sample ① ~ NUMPY ~
neo4j sandbox part 11
Install Numpy + atlas
Python3 Beginning Part 1
[Python] Numpy memo
Python: Scraping Part 2
pandas series part 1
Introduction to Python numpy pandas matplotlib (~ towards B3 ~ part2)