You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将GeoDataFrame列的numpy float64转换为常规float类型?

Answer

Absolutely, you don't need to iterate through the column manually—Pandas/GeoPandas has optimized vectorized methods to handle this conversion efficiently.

The core problem here is that JSON's default serializer doesn’t recognize numpy-specific data types like numpy.float64. To fix this without explicit looping, you can convert the GeoDataFrame column directly to a list of native Python floats using the tolist() method. This operation processes the entire column in one go, leveraging Pandas' internal optimizations instead of manual iteration.

Here’s how to adjust your code:

trajectory_features['points'][fid] = gdf[key].tolist()

If you need to retain the data as a Pandas Series (rather than a list) but with native Python float objects, you can use astype(object) to convert the column’s dtype:

# Convert the column to store Python float objects
gdf[key] = gdf[key].astype(object)
# Still convert to a list for JSON compatibility
trajectory_features['points'][fid] = gdf[key].tolist()

Another alternative is to create a custom JSON encoder that handles numpy types directly, which avoids modifying your data upfront. This is useful if you’re serializing the entire trajectory_features dictionary:

import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.float64):
            return float(obj)
        return super().default(obj)

# Serialize using the custom encoder
json_output = json.dumps(trajectory_features, cls=NumpyEncoder)

For your specific code snippet, though, using tolist() is the most straightforward way to get native Python floats into your dictionary without manual loops.

内容的提问来源于stack exchange,提问作者Jordan Rose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:49:12