问题
I have a dataframe with two columns, one called 'name' that is a string, and one called 'route' that is a Google polyline. I'm using the polyline library to decode the polyline into lat/long. I want to loop over each row to decode but it only seems to decode only the first row and write it to the rest of the created column. This is what I have so far.
df = pd.DataFrame(activities)
for row in df.itertuples(index=False):
name = row[0]
route = row[1]
try:
decoded = polyline.decode(route.replace('\\\\','\\'), geojson=True)
df['decode'] = df.apply(lambda route: [decoded], axis=1)
except:
print(name)
回答1:
Use DataFrame.apply with function:
df = pd.DataFrame(activities)
def decoder(name, route):
try:
return polyline.decode(route.replace('\\\\','\\'), geojson=True)
except:
print (name)
return np.nan
df['decode'] = df.apply(lambda x: decoder(x[0], x[1]), axis=1)
来源:https://stackoverflow.com/questions/61134046/writing-to-a-dataframe-through-a-loop