59_Pandas は describe を使用して、各列の要約統計 (平均、標準偏差など) を取得します。
pandas.DataFrame と pandas.Series の describe() メソッドを使用すると、各列の平均、標準偏差、最大、最小、最頻値などの要約統計を取得できます。
ここでは、以下の内容について説明する。
- describe() の基本的な使い方
- 対象のタイプを指定: 含める、除外する
- 文字列など、数値以外の列を指定する
- すべてのタイプの列を指定する
- 任意のタイプを選択/除外
- describe() アイテムの意味と対応する個々のメソッド
- count: 要素の数
- unique: 一意の値を持つ要素の数
- 上:モード
- freq: モード (出現回数)
- 平均: 算術平均
- std: 標準偏差
- min: 最小値
- max: 最大値
- 50%:中位数
- 25%、75%:1/4 分位数、3/4 分位数
- パーセンタイルの増分を指定
- 数値列の頻度などを計算します。
- 数値列の平均、標準偏差などを計算します
- pandas.Series の describe()
- 日時(datetime64[ns]型)
- 行に describe() を適用します
サンプルコードでは、各列の型が異なる dtype を持つ pandas.DataFrame を例にしています。
import pandas as pd
df = pd.DataFrame({
'a': [1, 2, 1, 3],
'b': [0.4, 1.1, 0.1, 0.8],
'c': ['X', 'Y', 'X', 'Z'],
'd': ['3', '5', '2', '1'],
'e': [True, True, False, True]})
print(df)
# a b c d e
# 0 1 0.4 X 3 True
# 1 2 1.1 Y 5 True
# 2 1 0.1 X 2 False
# 3 3 0.8 Z 1 True
print(df.dtypes)
# a int64
# b float64
# c object
# d object
# e bool
# dtype: object
describe() の基本的な使い方
対象のタイプを指定: 含める、除外する
文字列など、数値以外の列を指定する
すべてのタイプの列を指定する
任意のタイプを選択/除外
describe() アイテムの意味と対応する個々のメソッド
count: 要素の数
unique: 一意の値を持つ要素の数
上:モード
freq: モード (出現回数)
平均: 算術平均
std: 標準偏差
min: 最小値
max: 最大値
50%:中位数
25%、75%:1/4 分位数、3/4 分位数
パーセンタイルの増分を指定
数値列の頻度などを計算します。
数値列の平均、標準偏差などを計算します
pandas.Series の describe()
日時(datetime64[ns]型)
行に describe() を適用します
describe() の基本的な使い方
pandas.DataFrame の例で引数を指定せずに describe() メソッドを呼び出すと、結果が pandas.DataFrame として返されます。
print(df.describe())
# a b
# count 4.000000 4.000000
# mean 1.750000 0.600000
# std 0.957427 0.439697
# min 1.000000 0.100000
# 25% 1.000000 0.325000
# 50% 1.500000 0.600000
# 75% 2.250000 0.875000
# max 3.000000 1.100000
print(type(df.describe()))
# <class 'pandas.core.frame.DataFrame'>
行と要素は、loc と at を使用して取得できます。
print(df.describe().loc['std'])
# a 0.957427
# b 0.439697
# Name: std, dtype: float64
print(df.describe().at['std', 'b'])
# 0.439696865275764
pandas.DataFrame にはさまざまな種類の列がありますが、デフォルトでは数値列 (整数型 int、浮動小数点型 float) のみが選択され、平均値や標準偏差 std などの項目が計算されます。項目の意味については後述します。
判定は厳密に型 dtype に基づいているため、例の列 d のような数値文字列の列は除外されます。
欠損値 NaN は計算から除外されます。
対象のタイプを指定: 含める、除外する
数値以外の列の要約統計を取得するには、パラメータ include および exclude を設定します。
include は結果に含めるタイプを指定し、exclude は結果から除外するタイプを指定します。列名ではなく、型が指定されていることに注意してください。
文字列など、数値以外の列を指定する
数値型は 'number' で表されるため、exclude='number' を使用すると、文字列型などの非数値列の結果が計算されます。
print(df.describe(exclude='number'))
# c d e
# count 4 4 4
# unique 3 4 2
# top X 3 True
# freq 2 1 3
結果からわかるように、値やその他の計算項目が異なります。項目の意味については後述します。
さらに、pandas.DataFrame に数値列が含まれていない場合は、パラメーターを設定しないこともできます。
df_notnum = df[['c', 'd', 'e']]
print(df_notnum)
# c d e
# 0 X 3 True
# 1 Y 5 True
# 2 X 2 False
# 3 Z 1 True
print(df_notnum.dtypes)
# c object
# d object
# e bool
# dtype: object
print(df_notnum.describe())
# c d e
# count 4 4 4
# unique 3 4 2
# top X 3 True
# freq 2 1 3
すべてのタイプの列を指定する
include='all' の場合、すべてのタイプの列を含めます。
print(df.describe(include='all'))
# a b c d e
# count 4.000000 4.000000 4 4 4
# unique NaN NaN 3 4 2
# top NaN NaN X 3 True
# freq NaN NaN 2 1 3
# mean 1.750000 0.600000 NaN NaN NaN
# std 0.957427 0.439697 NaN NaN NaN
# min 1.000000 0.100000 NaN NaN NaN
# 25% 1.000000 0.325000 NaN NaN NaN
# 50% 1.500000 0.600000 NaN NaN NaN
# 75% 2.250000 0.875000 NaN NaN NaN
# max 3.000000 1.100000 NaN NaN NaN
ただし、数値列とそれ以外の種類の列では計算項目が異なるため、計算されない項目の値は欠損値 NaN になります。
任意のタイプを選択/除外
パラメータ include および exclude には、任意の型を指定できます。結果が 1 列しかない場合でも、pandas.DataFrame 型が返されます。
print(df.describe(include=int))
# a
# count 4.000000
# mean 1.750000
# std 0.957427
# min 1.000000
# 25% 1.000000
# 50% 1.500000
# 75% 2.250000
# max 3.000000
print(type(df.describe(include=int)))
# <class 'pandas.core.frame.DataFrame'>
リストには複数のタイプを指定できます。計算する項目は、選択したタイプによって自動的に決定されます。
print(df.describe(include=[object, bool]))
# c d e
# count 4 4 4
# unique 3 4 2
# top X 3 True
# freq 2 1 3
print(df.describe(exclude=[float, object]))
# a e
# count 4.000000 4
# unique NaN 2
# top NaN True
# freq NaN 3
# mean 1.750000 NaN
# std 0.957427 NaN
# min 1.000000 NaN
# 25% 1.000000 NaN
# 50% 1.500000 NaN
# 75% 2.250000 NaN
# max 3.000000 NaN
'number' と 'all' は引用符 ' または " で囲む必要がありますが、int や float などの Python の標準組み込み型は、引用符なしで include=int として指定できます。include='int' は問題ありません。
describe() アイテムの意味と対応する個々のメソッド
describe() によって計算されるアイテムの意味と、各アイテムを個別に数えたい場合に使用できるメソッドについて説明します。
describe() で取得した pandas.DataFrame の行を loc[] で指定すれば、各項目の値を選択できますが、それ以外の項目が不要な場合、メソッドだけを使うのはもったいないです。
前述のように、describe() で計算される項目は、値とその他の型で異なることに注意してください。また、describe()では、どの項目の計算でも欠損値 NaN は除外されます。
count: 要素の数
count() メソッドを使用して個別にカウントできます。
print(df.count())
# a 4
# b 4
# c 4
# d 4
# e 4
# dtype: int64
unique: 一意の値を持つ要素の数
nunique() メソッドを使用して個別に計算できます。
mode() は pandas.DataFrame を返します。同じ頻度の値がある場合、複数のパターンがあり、列ごとのパターンの数が異なります。
print(df.nunique())
# a 3
# b 4
# c 3
# d 4
# e 2
# dtype: int64
上:モード
mode() メソッドを使用して個別に計算できます。
print(df.mode())
# a b c d e
# 0 1.0 0.1 X 1 True
# 1 NaN 0.4 NaN 2 NaN
# 2 NaN 0.8 NaN 3 NaN
# 3 NaN 1.1 NaN 5 NaN
各列のモーダル値の数は、欠損値 NaN ではない要素の数をカウントする mode() の結果に count() メソッドを適用することで取得できます。
print(df.mode().count())
# a 1
# b 4
# c 1
# d 4
# e 1
# dtype: int64
iloc[0] を使用して最初の行を選択すると、各列は少なくとも 1 つのモード値を取得できます。
print(df.mode().iloc[0])
# a 1
# b 0.1
# c X
# d 1
# e True
# Name: 0, dtype: object
describe() のアイテム top に複数のモード値がある場合、そのうちの 1 つだけが返されますが、mode() の最初の行と常に一致するとは限らないことに注意してください。
freq: モード (出現回数)
pandas.Series の value_counts() メソッドを使用して個別にカウントできます。
value_counts() は、一意の要素値が index で頻度 (出現回数) が data である pandas.Series を返します。
デフォルトでは、pandas.Series は発生順にソートされるため、value_counts() メソッドによって返される pandas.Series の最初の値はパターンの頻度です。
print(df['c'].value_counts().iat[0])
# 2
pandas.DataFrame の各列のモード頻度を取得する場合は、apply() メソッドを使用して、value_counts() メソッドの結果の最大値を返す匿名関数を各列に適用します。
print(df.apply(lambda x: x.value_counts().iat[0]))
# a 2
# b 1
# c 2
# d 1
# e 3
# dtype: int64
value_counts() では、元の pandas.Series の要素は、結果の pandas.Series へのインデックスです。値がindexの場合、[number]で値を指定することはできません(エラーが報告されます)ので、iat [number]で厳密に指定してください。
平均: 算術平均
mean() メソッドを使用して個別に計算できます。
パラメータ numeric_only=True は、数値列のみを生成します。以下の方法は同じです。
print(df.mean(numeric_only=True))
# a 1.75
# b 0.60
# e 0.75
# dtype: float64
bool 型の列は describe() では除外されますが、mean() では True=1、False=0 として扱われます。以下の方法は同じです。
std: 標準偏差
n-1 で割った値。サンプル標準偏差とも呼ばれます。
std() メソッドを使用して個別に計算できます。
print(df.std(numeric_only=True))
# a 0.957427
# b 0.439697
# e 0.500000
# dtype: float64
min: 最小値
min() メソッドを使用して個別に計算できます。
print(df.min(numeric_only=True))
# a 1.0
# b 0.1
# e 0.0
# dtype: float64
max: 最大値
max() メソッドを使用して個別に計算できます。
print(df.max(numeric_only=True))
# a 3.0
# b 1.1
# e 1.0
# dtype: float64
50%:中位数
1/2 分位または 50 パーセンタイルとも呼ばれます。
median() メソッドで個別に計算できます。
print(df.median(numeric_only=True))
# a 1.5
# b 0.6
# e 1.0
# dtype: float64
25%、75%:1/4 分位数、3/4 分位数
第 1 四分位、第 3 四分位、25 パーセンタイル、75 パーセンタイルなどとも呼ばれます。
quantile() メソッドを使用して個別に計算できます。計算するパーセンタイルのリストを 0 から 1 の範囲で指定します。
print(df.quantile(q=[0.25, 0.75], numeric_only=True))
# a b e
# 0.25 1.00 0.325 0.75
# 0.75 2.25 0.875 1.00
quantile() を使用して、最小値、最大値、および中央値を一度に計算することもできます。
print(df.quantile(q=[0, 0.25, 0.5, 0.75, 1], numeric_only=True))
# a b e
# 0.00 1.00 0.100 0.00
# 0.25 1.00 0.325 0.75
# 0.50 1.50 0.600 1.00
# 0.75 2.25 0.875 1.00
# 1.00 3.00 1.100 1.00
計算されるパーセンタイルは、次のパラメーター パーセンタイルを使用して describe() で指定することもできます。
パーセンタイルの増分を指定
前の例のように、describe() はデフォルトで、最小 (0 パーセンタイル)、中央値 (50 パーセンタイル)、最大 (100 パーセンタイル)、および 25 パーセンタイルと 75 パーセンタイルを計算します。
最小値、中央値、最大値は常に計算されますが、他の値はパラメーター パーセンタイルを使用して指定できます。0 から 1 の範囲の値のリストを指定します。
print(df.describe(percentiles=[0.2, 0.4, 0.6, 0.8]))
# a b
# count 4.000000 4.000000
# mean 1.750000 0.600000
# std 0.957427 0.439697
# min 1.000000 0.100000
# 20% 1.000000 0.280000
# 40% 1.200000 0.480000
# 50% 1.500000 0.600000
# 60% 1.800000 0.720000
# 80% 2.400000 0.920000
# max 3.000000 1.100000
数値列の頻度などを計算します。
例えば、男性を0、女性を1としたカテゴリデータや、数値に地名を割り当てたデータでは、数値であっても平均や標準偏差ではなく最頻値や頻度を調べたい場合があります。データ。
print(df.astype('str').describe())
# a b c d e
# count 4 4 4 4 4
# unique 3 4 3 4 2
# top 1 1.1 X 3 True
# freq 2 1 2 1 3
print(df.astype({
'a': str}).describe(exclude='number'))
# a c d e
# count 4 4 4 4
# unique 3 3 4 2
# top 1 X 3 True
# freq 2 2 1 3
数値列の平均、標準偏差などを計算します
同様に、数値の文字列の平均または標準偏差を計算する場合は、astype() メソッドを使用します。
print(df.astype({
'd': int, 'e': int}).describe())
# a b d e
# count 4.000000 4.000000 4.000000 4.00
# mean 1.750000 0.600000 2.750000 0.75
# std 0.957427 0.439697 1.707825 0.50
# min 1.000000 0.100000 1.000000 0.00
# 25% 1.000000 0.325000 1.750000 0.75
# 50% 1.500000 0.600000 2.500000 1.00
# 75% 2.250000 0.875000 3.500000 1.00
# max 3.000000 1.100000 5.000000 1.00
pandas.Series の describe()
pandas.Series には describe() メソッドもあります。pandas.Series を返します。
s_int = df['a']
print(s_int)
# 0 1
# 1 2
# 2 1
# 3 3
# Name: a, dtype: int64
print(s_int.describe())
# count 4.000000
# mean 1.750000
# std 0.957427
# min 1.000000
# 25% 1.000000
# 50% 1.500000
# 75% 2.250000
# max 3.000000
# Name: a, dtype: float64
print(type(s_int.describe()))
# <class 'pandas.core.series.Series'>
パラメータ include および exclude は無視され、項目はタイプ dtype に従って計算されます。型変換には astype() を使用することもできます。
s_str = df['d']
print(s_str.describe())
# count 4
# unique 4
# top 3
# freq 1
# Name: d, dtype: object
print(s_str.astype('int').describe())
# count 4.000000
# mean 2.750000
# std 1.707825
# min 1.000000
# 25% 1.750000
# 50% 2.500000
# 75% 3.500000
# max 5.000000
# Name: d, dtype: float64
日時(datetime64[ns]型)
datetime64[ns] 型の列の最初と最後の項目を追加しました。
df['dt'] = pd.to_datetime(['2018-01-01', '2018-03-15', '2018-02-20', '2018-03-15'])
print(df.dtypes)
# a int64
# b float64
# c object
# d object
# e bool
# dt datetime64[ns]
# dtype: object
print(df.describe(include='datetime'))
# dt
# count 4
# unique 3
# top 2018-03-15 00:00:00
# freq 2
# first 2018-01-01 00:00:00
# last 2018-03-15 00:00:00
文字通り、first は最初の日付を意味し、last は最後の日付を意味します。min() と max() で別々に計算できます。
print(df['dt'].min())
# 2018-01-01 00:00:00
print(df['dt'].max())
# 2018-03-15 00:00:00
行に describe() を適用します
describe() は、行軸と列軸を指定する引数を取りません。.T を使用して転置し、describe() を呼び出して元の行の結果を取得します。
print(df.T.describe())
# 0 1 2 3
# count 6 6 6 6
# unique 5 6 6 6
# top 1 2018-03-15 00:00:00 2018-02-20 00:00:00 2018-03-15 00:00:00
# freq 2 1 1 1
pandasでは各列にdtypeという型があるので、基本的には各列が同じ型のデータで並んでいることが前提となります。
したがって、通常、行ごとに要約統計を取得する必要はなく、各行が同じ種類のデータで配置されている場合は転置した方がよいため、describe() だけでなく、あらゆる処理が容易になります。 .