通过循环写入数据框 [英] Writing to a dataframe through a loop

查看:47
本文介绍了通过循环写入数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的数据框,其中一列称为名称",它是一个字符串,一列称为"route",这是Google折线.我正在使用折线库将折线解码为经/纬度.我想遍历每一行进行解码,但似乎只解码第一行并将其写入创建的列的其余部分.这就是我到目前为止所拥有的.

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)

推荐答案

使用

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)

这篇关于通过循环写入数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆