问题
I have a pandas dataframe I would like to iterate over. For instance a simplified version of my dataframe can be:
abc begin end ID Lat Long
def1 001 123 CAT 13.167 52.411
def2 002 129 DOG 13.685 52.532
def3 003 145 MOOSE 13.698 52.131
def1 004 355 CAT 13.220 52.064
def2 005 361 CAT 13.304 52.121
def3 006 399 DOG 12.020 52.277
def1 007 411 MOOSE 13.699 52.549
def2 008 470 MOOSE 11.011 52.723
I would like to iterate over each unique ID and create a (shapely)LineString from the matching Lat / Long columns.
grp = df.groupby('ID')
for x in grp.groups.items():
# this is where I need the most help
For the above example I would like to get three iterations with 3 LineStrings put back into a single dictionary.
{'CAT':LINESTRING (13.167 52.411, 13.22 52.064, 13.304 52.121), 'DOG':LINESTRING (13.685 52.532, 12.02 52.277), 'MOOSE':LINESTRING (13.698 52.131, 12.699 52.549, 13.011 52.723)}
回答1:
I don't have the LINESTRING package installed, but I guess you can easily convert what's in d into the format you need.
d = {}
df.groupby('ID').apply(lambda x: d.update({x.ID.iloc[0]:x[['Lat','Long']].values.tolist()}))
{'CAT': [[13.167, 52.411], [13.22, 52.064], [13.304, 52.121]],
'DOG': [[13.685, 52.532], [12.02, 52.277]],
'MOOSE': [[13.698, 52.131], [13.699, 52.549], [11.011, 52.723]]}
来源:https://stackoverflow.com/questions/44181883/create-linestring-for-unique-values-in-pandas-dataframe