Python Numpy1 array

Contents

• Import Numpy
• Create 1 dim array
• Numpy array methods

Import Numpy

import numpy as np

After this, you can use numpy as np

np.xxxx

First time, it take times to load numpy library (only first time)

Create 1 dim array

We can create Numpy array from Python array

data = np.array([1,2,3,4,5,6,7,8,0,10])
print(data)
print(data.dtype)  # int64

a = np.zeros(3)
print(a)

b = np.ones(3)
print(b)

Convert type in array

a = np.array([1.0, 1.5, 2.0])
e = np.array(a, dtype=complex)
print(e.dtype)

Numpy array methods

Dimension

# Dimension
data = np.array([1,2,3,4,5,6,7,8,0,10])
print('Dim:', data.ndim)

Size

# Size
data = np.array([1,2,3,4,5,6,7,8,0,10])
print('Size:', data.size)

Sort

# Sort
data = np.array([10, 9, 8, 7, 6, 5, 4, 3, 1, 6])
data.sort()
print(data)  # [ 1  3  4  5  6  6  7  8  9 10]

Reverse

# Reverse
data = np.array([10, 9, 8, 7, 6, 5, 4, 3, 1, 6])
data[::-1].sort() # Sort : [ 1  3  4  5  6  6  7  8  9 10] and Reverse
print(data)  # [10  9  8  7  6  6  5  4  3  1]

Max

data = np.array([10, 9, 8, 7, 6, 5, 4, 3, 1, 6])
print('Max:', data.max())

Total

# Total
data = np.array([10, 9, 8, 7, 6, 5, 4, 3, 1, 6])
print('Sum:', data.sum())

Cum

# Cum
data = np.array([10, 9, 8, 7, 6, 5, 4, 3, 1, 6])
print('Cum:', data.cumsum())
スポンサーリンク
Professional Programmer2