配列の属性と確認
ndim、shape、size、dtype属性を調べ、reshape()で配列の形状を変更する方法を学びます。
「配列の属性と確認」はCoddyKit上の無料Pandas & NumPy Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPandas & NumPy Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Pandas & NumPy Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Array Attributes Matter
Before working on an array, you'll want to know its shape, dimensions, and dtype. NumPy hands you these instantly through lightweight attributes.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print('ndim:', a.ndim) # 2
print('shape:', a.shape) # (2, 3)
print('size:', a.size) # 6
print('dtype:', a.dtype) # int64ndim: Number of Dimensions
ndim tells you how many dimensions an array has: a flat list is 1, a list of lists is 2, and ML tensors often go to 3 or 4.
import numpy as np
v = np.array([1, 2, 3])
print(v.ndim) # 1
m = np.zeros((4, 5))
print(m.ndim) # 2
t = np.ones((2, 3, 4))
print(t.ndim) # 3shape: The Dimension Tuple
shape is a tuple with one size per dimension. For a 2-D array, that's (rows, columns) — and you can unpack it to write flexible code.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a.shape) # (2, 3, 4)
n_rows, n_cols = np.zeros((5, 7)).shape
print(n_rows, n_cols) # 5 7size: Total Number of Elements
size gives the total element count — every value in shape multiplied together. Handy for double-checking a reshape didn't lose anything.
import numpy as np
a = np.ones((3, 4, 5))
print(a.size) # 60 (3*4*5)
print(np.prod(a.shape))# 60
# Memory estimate in bytes
print(a.size * a.itemsize, 'bytes') # 480 bytesdtype: Element Data Type
The dtype describes each element's type, and itemsize tells you its byte size. Switching float64 to float32 halves memory and often runs faster.
import numpy as np
a = np.array([1.5, 2.5, 3.5])
print(a.dtype) # float64
print(a.itemsize) # 8 bytes
b = a.astype(np.float32)
print(b.dtype) # float32
print(b.itemsize) # 4 bytesnbytes: Total Memory Usage
nbytes is the array's total memory in bytes — just size times itemsize. Check it before and after downcasting to confirm you actually saved space.
import numpy as np
a = np.ones((1000, 1000), dtype=np.float64)
print(a.nbytes) # 8000000 (8 MB)
b = a.astype(np.float32)
print(b.nbytes) # 4000000 (4 MB)reshape(): Changing Array Shape
reshape gives the array a new shape without copying data, as long as the element count stays the same. Pass -1 and NumPy figures out that dimension for you.
import numpy as np
a = np.arange(12)
print(a.shape) # (12,)
b = a.reshape(3, 4)
print(b.shape) # (3, 4)
c = a.reshape(2, -1) # -1 inferred as 6
print(c.shape) # (2, 6)Flattening with ravel() and flatten()
Both ravel() and flatten() squash an array down to 1-D. The difference: ravel usually shares memory (no copy), while flatten always makes a fresh copy.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
r = m.ravel() # view (usually)
f = m.flatten() # always a copy
print(r) # [1 2 3 4 5 6]
print(f) # [1 2 3 4 5 6]Transposing Arrays
The .T attribute gives you the transpose — rows and columns swapped. It's free (no data copied) and essential for lining up matrices.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3)
print(m.T.shape) # (3, 2)
print(m.T)
# [[1 4]
# [2 5]
# [3 6]]strides: Memory Layout
strides show how many bytes NumPy steps through memory per dimension. This is why transposing is free — it just swaps the stride values.
import numpy as np
a = np.ones((3, 4), dtype=np.float64)
print(a.strides) # (32, 8) — 4 cols x 8 bytes, 1 col x 8 bytes
b = a.T
print(b.strides) # (8, 32) — strides swapped, no data copyChecking Views vs Copies
A view shares memory with the original, so changing one changes both; a copy is independent. Use np.shares_memory(a, b) to check which you have.
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3) # view
print(np.shares_memory(a, b)) # True
c = a.copy()
print(np.shares_memory(a, c)) # FalseQuick Check
Test your understanding of NumPy array attributes from this lesson.
Lesson Recap
Great progress! ndim, shape, and size describe structure, dtype describes the data, and reshape returns a view while flatten always copies. Next: array math.
よくある質問
「配列の属性と確認」レッスンは無料ですか?
はい。「配列の属性と確認」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Pandas & NumPy Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Pandas & NumPy Academyコースには全4レッスンが含まれています。
「配列の属性と確認」で何を学びますか?
ndim、shape、size、dtype属性を調べ、reshape()で配列の形状を変更する方法を学びます。 ブラウザで直接実行するハンズオンコードでPandas & NumPy Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Pandas & NumPy Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのPandas & NumPy Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「配列の属性と確認」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このPandas & NumPy Academyレッスンでコードを書いて実行できますか?
はい。すべてのPandas & NumPy Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。