Python の shape メソッドは、このメソッドが適用された Python オブジェクトの次元を表す tuple を返します。
shapeメソッドが適用される Python オブジェクトは、通常numpy.arrayやpandas.DataFrameといったオブジェクトです。
shape メソッドが返すタプルの要素数は、Pythonオブジェクトの次元数と等しくなります。
各 tuple 要素は、Python オブジェクトのその次元に対応する要素数を表します。
Pandas: shape メソッド
Pandas の shape メソッドは、DataFrame の寸法(行と列)を表す tuple を返します。
1. DataFrameの寸法を確認する
# Import Pandas Python moduleimport pandas as pd
# Create a Python listls =[['A','B','C','D'], ['e' ,'f' ,'g' ,'h'], [11, 22, 33, 44]]
# Create a Pandas DataFrame from the above listdf = pd.DataFrame(ls)
# Print the DataFrameprint(df)
# Check the dimensions of the DataFrameprint(df.shape)
|
結果を出力すると、以下の様になります。
0 1 2 3
0 A B C D 1 e f g h 2 11 22 33 44 (3, 4) |
Shape` メソッドは、DataFrameが3行4列の2次元であることを示す2つの要素を持つタプル (3, 4) を返します。
2. 空のDataFrameの寸法を確認する
# Import Pandas Python moduleimport pandas as pd
# Create an empty Pandas DataFramedf = pd.DataFrame()
# Print the DataFrameprint(df)
# Check the dimensions of the empty DataFrameprint(df.shape)
|
結果を出力すると、以下の様になります。
Empty DataFrame Columns: [] Index: [] (0, 0) |
Shape`メソッドは、DataFrameが0行0列の2次元であることを示す2つの要素を持つタプル(0, 0)を返しています。
NumPy: shape メソッド
NumPy の shape メソッドは、 numpy array の次元を表す tuple を返す。
1. numpy配列の次元を確認する
# Import Python NumPy moduleimport numpy as np
# Define a numpy array with zero dimensionsarr = np.array([[[1,2] ,[3,5]], [[2,3] ,[4,7]], [[3,4] ,[5,8]]])
# Print the numpy arrayprint(arr)
# Check the dimensions of arrprint(arr.shape)
|
結果を出力すると、以下の様になります。
[[[1 2 3] [3 5 6]]]
(1, 2, 3) |
Shape` メソッドは、配列が3つの次元を持ち、各次元がそれぞれ1、2、3の要素を持つことを示す、3つの要素を持つタプル (1、2、3) を返しました。
2. 0次元のnumpy配列の次元を確認する
# Import Python NumPy moduleimport numpy as np
# Define a numpy array with zero dimensionsarr = np.array(0)
# Print the numpy arrayprint(arr)
# Check the dimensions of arrprint(arr.shape)
|
出力せよ。
0 () |
Shape` メソッドは、配列の次元がゼロであることを示す、要素数ゼロの空のタプル () を返しました。
この記事もチェック:Numpyとvstackメソッドを使って1次元配列を多次元配列に結合する方法
3. 次元で要素が0個のnumpy配列の次元を確認する
# Import Python NumPy moduleimport numpy as np
# Define a numpy array from an empty listarr = np.array([])
# Print the numpy arrayprint(arr)
# Check the dimensions of arrprint(arr.shape)
|
出力せよ。
[] (0,) |
Shape` メソッドは、配列が1次元で要素が0であることを示す、1つの要素を持つタプル (0,) を返しました。
まとめ
この記事では、Pythonのオブジェクト(NumPy配列またはPandas DataFrame)の次元を調べるために、Pythonのshapeメソッドを使用する方法を学びました。
この記事もチェック:PandasのDataFrameをNumpyの配列に変換する方法