Im trying to create a .geojson
file from DataFrame
. I haver this table:
long lat elev
0 40.392987 -3.652552 0.0
1 41.471062 2.041841 0.0
2 41.410016 2.175180 0.0
3 NaN NaN NaN
And this is the function for create .geojson
file
def data2geojson(df):
features = []
df.apply(lambda X: features.append(
geojson.Feature(geometry=geojson.Point((X["lat"],
X["long"],
X["elev"])),
properties={"country": "Spain"})), axis=1)
with open('map.geojson', 'w') as fp:
geojson.dump(geojson.FeatureCollection(features), fp, sort_keys=True)
This code works if I only select the first three columns but throws the next error:
Out of range float values are not JSON compliant: nan
I dont know how to handle this more than with try:
and except ValueError:
But throwing an exception break the function and cant continue if there are more values...How can I handle this??
This error comes from the fact that JSON does not accept NaN values (which are considered float
in Python by the way). Before converting it to geojson you then need to edit these values in your input dataframe.
Depending on what you want to do with NaN values, you can fix this error with the following methods:
df = df.dropna()
0
:df = df.fillna(value=0)