Writing to a dataframe through a loop

試著忘記壹切 提交于 2021-01-28 19:27:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!