DataFrameの行数・列数を取得する【Python】

慣例に従って以下のようにpandasをインポートしているものとして進めていきます。

import pandas as pd

サンプルデータ

ここではseabornのirisデータセットを用います。

以下のようにしてデータを読み込んでください。

import seaborn as sns
df = sns.load_dataset('iris')

DataFrameのサマリーを取得する

infoメソッドを使用するとDataFrameのサマリーを表示することができます。なお、このメソッドはDataFrameのサマリーを標準出力に表示するのみで、それを値として取得することはできません。

df.info()

※ df : サンプルデータ

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
 #   Column        Non-Null Count  Dtype
---  ------        --------------  -----
 0   sepal_length  150 non-null    float64
 1   sepal_width   150 non-null    float64
 2   petal_length  150 non-null    float64
 3   petal_width   150 non-null    float64
 4   species       150 non-null    object
dtypes: float64(4), object(1)
memory usage: 6.0+ KB

infoメソッドにより、取得できる項目は以下の通りです。

  • 行数、列数
  • 各列における欠損値を除いた行数とデータ型
  • メモリー使用量

DataFrameの形状を取得する

DataFrameの行数/列数を取得する

DataFrameのshape属性を用いることで、行数/列数のタプルを取得できます。

print(df.shape)

※ df : サンプルデータ

(150, 5)

DataFrameの行数を取得する

Pythonの組み込み関数lenを用いることで、DataFrameの行数を取得できます。

print(len(df))

※ df : サンプルデータ

150

ここで得られる値は、shape属性を用いて

print(df.shape[0])

とするのと同一です。

DataFrameの列を取得する

DataFrameのcolumns属性を用いることで、DataFrameの列をIndexオブジェクトとして取得することができます。

print(df.columns)

※ df : サンプルデータ

Index(['sepal_length', 'sepal_width', 'petal_length', 'petal_width',
       'species'],
      dtype='object')

組み込み関数lenを組み合わせることで列数も取得できます。

print(len(df.columns))

※ df : サンプルデータ

5

この値はshape属性を用いて

print(df.shape[1])

とするのと同一です。

DataFrameの全要素数を取得する

DataFrameのsize属性を用いることで、その全要素数を取得することができます。

print(df.size)

※ df : サンプルデータ

750

この値は、行数 × 列数 に相当します。

スポンサーリンク

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)