NumPy配列作成と型変換の基本ガイド

配列の作成

np.array()を用いた配列作成

import numpy as np

# Pythonリストから1次元配列を生成
sample_list = np.array([5, 10, 15, 20])
print(sample_list)

# 2次元配列の作成(ネストしたリスト利用)
matrix_data = np.array([[7, 14], [21, 28]])
print(matrix_data)

# 型が異なる要素の自動変換
mixed_elements = np.array([10, 3.14, "text"])
print(mixed_elements.dtype)
[ 5 10 15 20]
[[ 7 14]
 [21 28]]

np.zeros()によるゼロ埋め配列

# フロート型の1次元ゼロ配列
zero_vector = np.zeros(4)
print(zero_vector)

# 整数型の3×2行列生成
integer_matrix = np.zeros((3, 2), dtype=int)
print(integer_matrix)
[0. 0. 0. 0.]
[[0 0]
 [0 0]
 [0 0]]

np.ones()を用いた1埋め配列

# 2行3列の浮動小数点型1埋め配列
ones_grid = np.ones((2, 3))
print(ones_grid)
[[1. 1. 1.]
 [1. 1. 1.]]

np.arange()による数値列生成

# 5から25まで3刻みの配列
step_sequence = np.arange(5, 25, 3)
print(step_sequence)

# 浮動小数点ステップの例(精度注意)
float_sequence = np.arange(0.5, 2.5, 0.4)
print(float_sequence)
[ 5  8 11 14 17 20 23]
[0.5 0.9 1.3 1.7 2.1]

np.linspace()による均等間隔配列

# 0からπまで10個の等間隔点
pi_points = np.linspace(0, np.pi, 10)
print(pi_points)

# サイン波サンプリング用のデータ生成
wave_samples = np.linspace(0, 2 * np.pi, 50)
[0.         0.34906585 0.6981317  1.04719755 1.3962634  1.74532925
 2.0943951  2.44346095 2.7925268  3.14159265]

配列の属性

shape:次元構造

multi_dim = np.array([[1, 2, 3], [4, 5, 6]])
print(multi_dim.shape)
(2, 3)

dtype:データ型確認

print(multi_dim.dtype)
float_array = np.array([1.0, 2.0, 3.0])
print(float_array.dtype)
int64
float64

ndim:次元数

print(multi_dim.ndim)
scalar_value = np.array(42)
print(scalar_value.ndim)
2
0

size:総要素数

print(multi_dim.size)
6

型変換処理

astype()メソッドの実装

# 整数→浮動小数点変換
int_array = np.array([10, 20, 30])
float_array = int_array.astype(np.float64)
print(float_array)

# 浮動小数点→整数(小数切り捨て)
float_values = np.array([9.9, 8.5, 7.1])
int_values = float_values.astype(int)
print(int_values)

# 整数→文字列変換
str_values = int_values.astype(str)
print(str_values)
[10. 20. 30.]
[9 8 7]
['9' '8' '7']

タグ: NumPy array-creation data-type dtype-conversion linspace

6月20日 17:02 投稿