groupby
和to_json
的組合似乎很好。
import pandas as pd
import numpy as np
import pprint
arrays = [np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4]),
np.array([1, 2, 3, 1, 2, 1, 2, 3, 4, 5, 1, 2])]
df = pd.DataFrame(np.arange(24).reshape(12,2),
index=arrays, columns=['Longitude', 'Lattitude'])
dd = {"type":"Feature",
"geometry":{"type":"Linestring",
"coordinates":None
},
"properties":{"prop0":'red',
"prop1":'dashed'
}
}
for _, group in df.groupby(level=0):
dd["geometry"]["coordinates"] = group.to_json(orient='values')
pprint.pprint(dd)
輸出:
{'geometry': {'coordinates': '[[0,1],[2,3],[4,5]]',
'type': 'Linestring'},
'properties': {'prop0': 'red',
'prop1': 'dashed'},
'type': 'Feature'}
{'geometry': {'coordinates': '[[6,7],[8,9]]',
'type': 'Linestring'},
'properties': {'prop0': 'red',
'prop1': 'dashed'},
'type': 'Feature'}
{'geometry': {'coordinates': '[[10,11],[12,13],[14,15],[16,17],[18,19]]',
'type': 'Linestring'},
'properties': {'prop0': 'red',
'prop1': 'dashed'},
'type': 'Feature'}
{'geometry': {'coordinates': '[[20,21],[22,23]]',
'type': 'Linestring'},
'properties': {'prop0': 'red',
'prop1': 'dashed'},
'type': 'Feature'}
非常感謝!你的代碼運作良好! – eapsclimate