Python Data Handling

TypeError: ‘int64’型オブジェクトはJSONシリアライズできません問題の解決方法

Spread the love

PythonでPandasやNumPyなどのライブラリを使用する際、「TypeError: Object of type ‘int64’ is not JSON serializable」というエラーがよく発生します。これは、JSONがNumPyの`int64`データ型をネイティブにサポートしていないことが原因です。このガイドでは、この問題を解決するためのソリューションを紹介します。

目次

`int64`を標準的なPython型に変換する

最も一般的で推奨される解決策は、`int64`値を標準的なPythonの整数型(`int`)または浮動小数点型(`float`)に変換することです。これにより、数値データが保持され、JSONとの互換性が確保されます。

Pandasの例:


import pandas as pd
import json

data = {'col1': [1, 2, 3, 4, 5, 2**63]}  # 大きな数値を含む
df = pd.DataFrame(data)

# intに変換 (大きな数値ではOverflowErrorが発生)
try:
    df['col1'] = df['col1'].astype(int)
    json_data = json.dumps(df.to_dict('records'))
    print(f"Integer conversion: {json_data}")
except OverflowError:
    print("OverflowError occurred during integer conversion.")

# floatに変換 (大きな数値を処理)
df['col1'] = df['col1'].astype(float)
json_data = json.dumps(df.to_dict('records'))
print(f"Float conversion: {json_data}")

NumPyの例:


import numpy as np
import json

arr = np.array([1, 2, 3, 4, 5, 2**63], dtype=np.int64)

# intに変換 (大きな数値ではOverflowErrorが発生)
try:
    arr = arr.astype(int)
    json_data = json.dumps(arr.tolist())
    print(f"Integer conversion: {json_data}")
except OverflowError:
    print("OverflowError occurred during integer conversion.")

# floatに変換 (大きな数値を処理)
arr = arr.astype(float)
json_data = json.dumps(arr.tolist())
print(f"Float conversion: {json_data}")

大きな数値の処理

`int64`値が標準的なPython整数で表現可能な最大値を超える可能性がある場合、`OverflowError`を回避するために`float`への変換が不可欠です。`float`ははるかに広い範囲の数値を処理できます。

`int64`を文字列に変換する

シリアライズ後にデータに対して数学演算を行う必要がない場合は、文字列への変換が簡単な代替手段となります。これは、潜在的なオーバーフローの問題を回避する堅牢なアプローチです。


import pandas as pd
import json

data = {'col1': [1, 2, 3, 4, 5, 2**63]}
df = pd.DataFrame(data)

df['col1'] = df['col1'].astype(str)
json_data = json.dumps(df.to_dict('records'))
print(json_data)

データシリアライゼーションのベストプラクティス

よりクリーンなコードと保守性の向上のため、シリアライズ前に一貫してデータ型を処理してください。データ構造が複雑な場合は、専用のシリアライゼーションライブラリを使用することを検討してください。特定のアプリケーションの要件に基づいて、適切な変換方法(int、float、または文字列)を常に慎重に選択してください。

コメントを残す

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