如何将GeoDataFrame列的numpy float64转换为常规float类型?
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

