pandas.DataFrameから特定の型dtypeの列を抽出(選択)
pandas.DataFrame
は列ごとにデータ型dtype
を保持している。
特定のデータ型dtype
の列だけを抽出(選択)するにはpandas.DataFrame
のメソッドselect_dtypes()
を使う。
以下の様々なデータ型の列をもつ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': [[0, 0], [0, 1], [1, 0], [1, 1]],
'e': [True, True, False, True]})
df['f'] = pd.to_datetime(['2018-01-01', '2018-03-15', '2018-02-20', '2018-03-15'])
print(df)
# a b c d e f
# 0 1 0.4 X [0, 0] True 2018-01-01
# 1 2 1.1 Y [0, 1] True 2018-03-15
# 2 1 0.1 X [1, 0] False 2018-02-20
# 3 3 0.8 Z [1, 1] True 2018-03-15
print(df.dtypes)
# a int64
# b float64
# c object
# d object
# e bool
# f datetime64[ns]
# dtype: object
ここでは以下の内容について説明する。
select_dtypes()
の基本的な使い方- 抽出する型を指定: 引数
include
- 除外する型を指定: 引数
exclude
- 抽出する型を指定: 引数
pandasのデータ型dtype
および型変換(キャスト)のためのastype()
メソッドについては以下の記事を参照。
select_dtypes()の基本的な使い方
抽出する型を指定: 引数include
引数include
に抽出するデータ型dtype
を指定する。
print(df.select_dtypes(include=int))
# a
# 0 1
# 1 2
# 2 1
# 3 3
int
やfloat
のようにPythonの組み込み型として用意されているものはそのまま指定できる。文字列として'int'
と指定してもいいし、厳密にビット数まで含めて'int64'
としてもいい。(標準のビット数は環境によって異なる)
print(df.select_dtypes(include='int'))
# a
# 0 1
# 1 2
# 2 1
# 3 3
print(df.select_dtypes(include='int64'))
# a
# 0 1
# 1 2
# 2 1
# 3 3
当然ながらビット数まで含める場合はビット数まで一致していないと選択されない。
print(df.select_dtypes(include='int32'))
# Empty DataFrame
# Columns: []
# Index: [0, 1, 2, 3]
リストで複数のデータ型dtype
を指定可能。日時datetime64[ns]
は'datetime'
で指定できる。
print(df.select_dtypes(include=[int, float, 'datetime']))
# a b f
# 0 1 0.4 2018-01-01
# 1 2 1.1 2018-03-15
# 2 1 0.1 2018-02-20
# 3 3 0.8 2018-03-15
int
やfloat
などの数値型は特殊な値'number'
でまとめて指定可能。
print(df.select_dtypes(include='number'))
# a b
# 0 1 0.4
# 1 2 1.1
# 2 1 0.1
# 3 3 0.8
文字列str
型を要素とする列のデータ型dtype
はobject
だが、object
列にはstr
以外のPython標準の組み込み型も含まれる。実際にはあまりないが、もし例のようにlist
型を要素とする列があった場合、include=object
ではその列も抽出されるので注意。
print(df.select_dtypes(include=object))
# c d
# 0 X [0, 0]
# 1 Y [0, 1]
# 2 X [1, 0]
# 3 Z [1, 1]
print(type(df.at[0, 'c']))
# <class 'str'>
print(type(df.at[0, 'd']))
# <class 'list'>
もっとも、意図的に処理しない限り文字列str
型以外のobject
がpandas.DataFrame
の要素となることは(多分)ないので、あまり気にする必要はないと思う。
除外する型を指定: 引数exclude
引数exclude
に除外するデータ型dtype
を指定する。リストで複数のデータ型dtype
を指定することもできる。
print(df.select_dtypes(exclude='number'))
# c d e f
# 0 X [0, 0] True 2018-01-01
# 1 Y [0, 1] True 2018-03-15
# 2 X [1, 0] False 2018-02-20
# 3 Z [1, 1] True 2018-03-15
print(df.select_dtypes(exclude=[bool, 'datetime']))
# a b c d
# 0 1 0.4 X [0, 0]
# 1 2 1.1 Y [0, 1]
# 2 1 0.1 X [1, 0]
# 3 3 0.8 Z [1, 1]
include
とexclude
は同時に指定可能だが、同じ型を指定するとエラー。
print(df.select_dtypes(include='number', exclude=int))
# b
# 0 0.4
# 1 1.1
# 2 0.1
# 3 0.8
# print(df.select_dtypes(include=[int, bool], exclude=int))
# ValueError: include and exclude overlap on frozenset({<class 'numpy.int64'>})