Properties in GeoJSON features can be lists (or "arrays" in Javascript). For example, the following GeoJSON feature is formatted correctly, and includes a values
property that is a list:
{
type: "Feature",
geometry: {
type: "Point",
coordinates: [149.043, -35.227],
},
properties: {
district: "Belconnen",
values: [0.62, 0.68, 0.74]
}
}
However, GeoPandas seems unable to handle properties that are lists. A value error is called if I try to write a list directly into a GeoDataFrame:
import geopandas as gpd
# define geodata
gdf = gpd.GeoDataFrame()
gdf["district"] = ["Belconnen", "Gungahlin", "Molonglo"]
gdf["geometry"] = gpd.points_from_xy(
[149.042, 149.131, 149.047],
[-35.227, -35.179, -35.295]
)
# attempt to write a list into GeoDataFrame cell
gdf.at["Belconnen", "values"] = [0.62, 0.68, 0.74]
This yields the following error:
ValueError: Must have equal len keys and value when setting with an iterable
I tried an alternative way around this problem: I converted a Pandas Dataframe, which does allow columns of lists, into a GeoDataFrame and then added the geometry
column later.
import pandas as pd, geopandas as gpd
# define dataframe
df = pd.DataFrame()
df["district"] = ["Belconnen", "Gungahlin", "Molonglo"]
df["values"] = [
[0.62, 0.68, 0.74],
[0.55, 0.61, 0.67],
[0.59, 0.66, 0.73]
]
# convert to geodataframe
gdf = gpd.GeoDataFrame(df)
gdf["geometry"] = gpd.points_from_xy(
[149.042, 149.131, 149.047],
[-35.227, -35.179, -35.295]
)
This appeared to work ...
... until I tried to write the GeoDataFrame to file:
gdf.to_file("gdf.geojson", driver="GeoJSON")
This yielded the following error:
ValueError: Invalid field type <class 'list'>
Can I get GeoPandas to work with columns of lists, or is that not possible?
GeoPandas uses fiona
to handle most of the stuff within read_file
and it seems that fiona is unable to handle list in this case.
But GeoPandas can also generate JSON by itself, and it seems that in that case, it works correctly.
Using that second gdf made from pandas:
>>> print(gdf.to_json(indent=4))
{
"type": "FeatureCollection",
"features": [
{
"id": "0",
"type": "Feature",
"properties": {
"district": "Belconnen",
"values": [
0.62,
0.68,
0.74
]
},
"geometry": {
"type": "Point",
"coordinates": [
149.042,
-35.227
]
}
},
{
"id": "1",
"type": "Feature",
"properties": {
"district": "Gungahlin",
"values": [
0.55,
0.61,
0.67
]
},
"geometry": {
"type": "Point",
"coordinates": [
149.131,
-35.179
]
}
},
{
"id": "2",
"type": "Feature",
"properties": {
"district": "Molonglo",
"values": [
0.59,
0.66,
0.73
]
},
"geometry": {
"type": "Point",
"coordinates": [
149.047,
-35.295
]
}
}
]
}