| 1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- """
- 工具函数模块
- """
- import numpy as np
- import pandas as pd
- def convert_to_native_types(obj):
- """递归地将 numpy/pandas 类型转换为 Python 原生类型,以便 JSON 序列化"""
- if isinstance(obj, (np.integer, np.int_, np.intc, np.intp, np.int8,
- np.int16, np.int32, np.int64, np.uint8, np.uint16,
- np.uint32, np.uint64)):
- return int(obj)
- elif isinstance(obj, (np.floating, np.float64, np.float16, np.float32, np.float64)):
- return float(obj)
- elif isinstance(obj, (np.bool_, np.bool)):
- return bool(obj)
- elif isinstance(obj, (np.ndarray, pd.Series)):
- return obj.tolist()
- elif isinstance(obj, pd.DataFrame):
- return obj.to_dict('records')
- elif isinstance(obj, dict):
- return {key: convert_to_native_types(value) for key, value in obj.items()}
- elif isinstance(obj, (list, tuple)):
- return [convert_to_native_types(item) for item in obj]
- elif isinstance(obj, (str, int, float, bool, type(None))):
- return obj
- else:
- try:
- return str(obj)
- except Exception:
- return obj
- def ensure_native_type(value, target_type=float, decimal_places=2):
- """确保值为 Python 原生类型,并保留指定小数位数"""
- if isinstance(value, (np.integer, np.floating)):
- converted = target_type(value)
- if target_type == float and decimal_places is not None:
- return round(converted, decimal_places)
- return converted
- if isinstance(value, float) and decimal_places is not None:
- return round(value, decimal_places)
- return value
|