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 this error:
ValueError: Invalid field type <class 'list'>
Can I get GeoPandas to work with columns of lists, or is that not possible?
df['values'] = df['values'].apply(lambda x: ','.join([str(y) for y in x]))