Pandas データ型(dtype と型変換)
Pandas は豊富なデータ型システムを提供しており、データ型を正しく理解して使用することは効率的なデータ分析の基本です。このセクションでは、Pandas のデータ型体系、型推論、型変換の方法について詳しく説明します。
Pandas データ型概要
| dtype | 説明 | Python 型 | 例 |
|---|---|---|---|
int64 |
64ビット整数 | int | 1, 2, 100 |
float64 |
64ビット浮動小数点数 | float | 1.5, 3.14 |
object |
文字列または混合型 | str | "hello" |
bool |
ブール値 | bool | True, False |
datetime64[ns] |
日時 | datetime | 2024-01-01 |
timedelta64[ns] |
時間差 | timedelta | 1 days |
category |
カテゴリ型 | - | 有限集合 |
例
import pandas as pd
import numpy as np
# さまざまなデータ型の DataFrame を作成
df = pd.DataFrame({
"整数": [1, 2, 3],
"浮動小数点数": [1.5, 2.5, 3.5],
"文字列": ["a", "b", "c"],
"ブール値": [True, False, True],
"日付": pd.date_range("2024-01-01", periods=3)
})
print("各列のデータ型:")
print(df.dtypes)
import numpy as np
# さまざまなデータ型の DataFrame を作成
df = pd.DataFrame({
"整数": [1, 2, 3],
"浮動小数点数": [1.5, 2.5, 3.5],
"文字列": ["a", "b", "c"],
"ブール値": [True, False, True],
"日付": pd.date_range("2024-01-01", periods=3)
})
print("各列のデータ型:")
print(df.dtypes)
型の推論と指定
自動型推論
例
import pandas as pd
# CSV 読み込み時の型推論
# pandas は各列に最適な型を推論しようとします
df = pd.read_csv("data.csv")
# または dtype パラメータで明示的に型を指定します
df = pd.read_csv("data.csv", dtype={
"年齢": "int32", # 32ビット整数に指定してメモリを節約
"給与": "float32", # 32ビット浮動小数点数に指定
"氏名": "string" # PyArrow 文字列を使用
})
# CSV 読み込み時の型推論
# pandas は各列に最適な型を推論しようとします
df = pd.read_csv("data.csv")
# または dtype パラメータで明示的に型を指定します
df = pd.read_csv("data.csv", dtype={
"年齢": "int32", # 32ビット整数に指定してメモリを節約
"給与": "float32", # 32ビット浮動小数点数に指定
"氏名": "string" # PyArrow 文字列を使用
})
作成時の型指定
例
import pandas as pd
import numpy as np
# データ型を指定して Series を作成
s = pd.Series([1, 2, 3], dtype="int8") # より小さい整数型を使用
print(f"int8 型:{s.dtype}")
s = pd.Series([1.5, 2.5, 3.5], dtype="float32") # float32 を使用
print(f"float32 型:{s.dtype}")
# numpy 型を使用
s = pd.Series([1, 2, 3], dtype=np.int8)
print(f"np.int8 型:{s.dtype}")
import numpy as np
# データ型を指定して Series を作成
s = pd.Series([1, 2, 3], dtype="int8") # より小さい整数型を使用
print(f"int8 型:{s.dtype}")
s = pd.Series([1.5, 2.5, 3.5], dtype="float32") # float32 を使用
print(f"float32 型:{s.dtype}")
# numpy 型を使用
s = pd.Series([1, 2, 3], dtype=np.int8)
print(f"np.int8 型:{s.dtype}")
型変換
astype を使用した変換
例
import pandas as pd
import numpy as np
# サンプルデータを作成
df = pd.DataFrame({
"整数": [1, 2, 3],
"浮動小数点数": [1.5, 2.5, 3.5],
"文字列": ["1", "2", "3"],
"ブール値": [1, 0, 1]
})
print("元の型:")
print(df.dtypes)
print()
# 文字列に変換
df["整数_str"] = df["整数"].astype(str)
print("文字列に変換後:")
print(df.dtypes)
# 文字列を数値に変換
df["文字列_int"] = df["文字列"].astype(int)
print("\n"文字列を整数に変換:")
print(df.dtypes)
# 数値をブール値に変換(0以外はTrue)
df["ブール_int"] = df["ブール値"].astype(bool)
print("\n"整数をブールに変換:")
print(df.dtypes)
# 浮動小数点数を整数に変換(切り捨て)
df["浮動小数点_int"] = df["浮動小数点数"].astype(int)
print("\n"浮動小数点数を整数に変換:")
print(df)
import numpy as np
# サンプルデータを作成
df = pd.DataFrame({
"整数": [1, 2, 3],
"浮動小数点数": [1.5, 2.5, 3.5],
"文字列": ["1", "2", "3"],
"ブール値": [1, 0, 1]
})
print("元の型:")
print(df.dtypes)
print()
# 文字列に変換
df["整数_str"] = df["整数"].astype(str)
print("文字列に変換後:")
print(df.dtypes)
# 文字列を数値に変換
df["文字列_int"] = df["文字列"].astype(int)
print("\n"文字列を整数に変換:")
print(df.dtypes)
# 数値をブール値に変換(0以外はTrue)
df["ブール_int"] = df["ブール値"].astype(bool)
print("\n"整数をブールに変換:")
print(df.dtypes)
# 浮動小数点数を整数に変換(切り捨て)
df["浮動小数点_int"] = df["浮動小数点数"].astype(int)
print("\n"浮動小数点数を整数に変換:")
print(df)
pd.to_numeric を使用した変換
例
import pandas as pd
import numpy as np
# 特殊文字を含む数値文字列を処理
s = pd.Series(["$1,000", "$2,500", "$3,200"])
# クリーンアップして変換
s_cleaned = s.str.replace("$", "", regex=False).str.replace(",", "", regex=False)
s_numeric = pd.to_numeric(s_cleaned)
print("文字列を数値に変換:")
print(s_numeric)
print(f"型: {s_numeric.dtype}")
print()
# 欠損値を処理
s_with_na = pd.Series(["1", "2", "NA", "4"])
s_numeric = pd.to_numeric(s_with_na, errors="coerce") # 無効な値を NaN に変換
print("欠損値の処理:")
print(s_numeric)
import numpy as np
# 特殊文字を含む数値文字列を処理
s = pd.Series(["$1,000", "$2,500", "$3,200"])
# クリーンアップして変換
s_cleaned = s.str.replace("$", "", regex=False).str.replace(",", "", regex=False)
s_numeric = pd.to_numeric(s_cleaned)
print("文字列を数値に変換:")
print(s_numeric)
print(f"型: {s_numeric.dtype}")
print()
# 欠損値を処理
s_with_na = pd.Series(["1", "2", "NA", "4"])
s_numeric = pd.to_numeric(s_with_na, errors="coerce") # 無効な値を NaN に変換
print("欠損値の処理:")
print(s_numeric)
pd.to_datetime を使用した日付変換
例
import pandas as pd
# さまざまな日付形式の変換
dates = ["2024-01-01", "2024/01/02", "01/03/2024", "20240104"]
# 日付に変換
dt = pd.to_datetime(dates, errors="coerce")
print("日付変換結果:")
print(dt)
print(f"型: {dt.dtype}")
print()
# 日付形式を指定
dates2 = ["20240101", "20240102", "20240103"]
dt2 = pd.to_datetime(dates2, format="%Y%m%d")
print("指定形式での変換:")
print(dt2)
# さまざまな日付形式の変換
dates = ["2024-01-01", "2024/01/02", "01/03/2024", "20240104"]
# 日付に変換
dt = pd.to_datetime(dates, errors="coerce")
print("日付変換結果:")
print(dt)
print(f"型: {dt.dtype}")
print()
# 日付形式を指定
dates2 = ["20240101", "20240102", "20240103"]
dt2 = pd.to_datetime(dates2, format="%Y%m%d")
print("指定形式での変換:")
print(dt2)
メモリ最適化
適切なデータ型を選択することで、メモリ使用量を大幅に削減できます。
整数型の選択
例
import pandas as pd
import numpy as np
# 大量データの Series を作成
s = pd.Series(np.random.randint(0, 100, 1000000))
# デフォルトは int64
print(f"int64 メモリ: {s.dtype} -> {s.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# より小さい型に変換
s_int8 = s.astype("int8")
print(f"int8 メモリ: {s_int8.dtype} -> {s_int8.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# データの範囲に応じて適切な型を選択
# np.iinfo で整数の範囲を確認
print(f"\nint8 範囲: {np.iinfo('int8').min} から {np.iinfo('int8').max}")
print(f"int16 範囲: {np.iinfo('int16').min} から {np.iinfo('int16').max}")
print(f"int32 範囲: {np.iinfo('int32').min} から {np.iinfo('int32').max}")
import numpy as np
# 大量データの Series を作成
s = pd.Series(np.random.randint(0, 100, 1000000))
# デフォルトは int64
print(f"int64 メモリ: {s.dtype} -> {s.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# より小さい型に変換
s_int8 = s.astype("int8")
print(f"int8 メモリ: {s_int8.dtype} -> {s_int8.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# データの範囲に応じて適切な型を選択
# np.iinfo で整数の範囲を確認
print(f"\nint8 範囲: {np.iinfo('int8').min} から {np.iinfo('int8').max}")
print(f"int16 範囲: {np.iinfo('int16').min} から {np.iinfo('int16').max}")
print(f"int32 範囲: {np.iinfo('int32').min} から {np.iinfo('int32').max}")
category 型の使用
例
import pandas as pd
import numpy as np
# 重複値が多い Series を作成
s = pd.Series(np.random.choice(["北京", "上海", "広州", "深セン"], 1000000))
# 文字列型
print(f"object 型メモリ: {s.dtype} -> {s.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# category 型に変換
s_cat = s.astype("category")
print(f"category 型メモリ: {s_cat.dtype} -> {s_cat.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# 欠点:一部の操作は遅くなる
print("\ncategory 情報:")
print(s_cat.cat.categories)
import numpy as np
# 重複値が多い Series を作成
s = pd.Series(np.random.choice(["北京", "上海", "広州", "深セン"], 1000000))
# 文字列型
print(f"object 型メモリ: {s.dtype} -> {s.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# category 型に変換
s_cat = s.astype("category")
print(f"category 型メモリ: {s_cat.dtype} -> {s_cat.memory_usage(deep=True) / 1024 / 1024:.2f} MB")
# 欠点:一部の操作は遅くなる
print("\ncategory 情報:")
print(s_cat.cat.categories)
型のチェックと判定
例
import pandas as pd
import numpy as np
df = pd.DataFrame({
"整数": [1, 2, 3],
"浮動小数点": [1.5, 2.5, 3.5],
"文字列": ["a", "b", "c"]
})
# データ型をチェック
print("数値型かどうかをチェック:")
print(df.dtypes)
# is_integer_dtype を使用
print(f"\n整数列: {pd.api.types.is_integer_dtype(df['整数'])}")
print(f"浮動小数点列: {pd.api.types.is_float_dtype(df['浮動小数点'])}")
print(f"文字列の列: {pd.api.types.is_object_dtype(df['文字列'])}")
# 数値に変換できるかチェック
print(f"\n"数値に変換可能か: {pd.api.types.is_numeric_dtype(df['整数'])}")
print(f"日時かどうか: {pd.api.types.is_datetime64_any_dtype(pd.Series(pd.date_range('2024', periods=3)))}")
import numpy as np
df = pd.DataFrame({
"整数": [1, 2, 3],
"浮動小数点": [1.5, 2.5, 3.5],
"文字列": ["a", "b", "c"]
})
# データ型をチェック
print("数値型かどうかをチェック:")
print(df.dtypes)
# is_integer_dtype を使用
print(f"\n整数列: {pd.api.types.is_integer_dtype(df['整数'])}")
print(f"浮動小数点列: {pd.api.types.is_float_dtype(df['浮動小数点'])}")
print(f"文字列の列: {pd.api.types.is_object_dtype(df['文字列'])}")
# 数値に変換できるかチェック
print(f"\n"数値に変換可能か: {pd.api.types.is_numeric_dtype(df['整数'])}")
print(f"日時かどうか: {pd.api.types.is_datetime64_any_dtype(pd.Series(pd.date_range('2024', periods=3)))}")
よくある質問
1、整数列に浮動小数点数が現れる
DataFrame に混入すると自動的に float64 に変換されます。使用Nullable Integer型を使用すると整数の欠損値を保持できます。
2、日付形式が統一されていない
使用pd.to_datetimeおよび指定formatパラメータで非標準形式を処理します
3、CSV読み取り時の型エラー
使用dtypeパラメータで型を明示的に指定するか、またはconverters変換してください。
その他の拡張大規模データセットでは、メモリ使用量を削減するために、より小さいデータ型(int8、int16、float32など)とcategory型の使用を優先してください。