SpindriftSeltzer
SpindriftSeltzer

Reputation: 321

Writing to a dataframe through a loop

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)

Upvotes: 1

Views: 139

Answers (1)

jezrael
jezrael

Reputation: 862406

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)

Upvotes: 1

Related Questions