应用函数未正确循环 Dataframe 中的列表

yzxexxkh  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(225)

我有一个数据框,看起来像下面的
客户节点客户a[3232132322213343243242,…]客户b[5759455453455435345,…]
我正在尝试使用apply函数来循环遍历客户机每个列表中的每个项目,并对每个数字运行该函数,因此首先对客户机a使用32321,然后对客户机a使用32312,然后将这两个结果都放在一个列表中,并在下一列中返回。
现在,我下面的函数从每行列表中获取第一项并应用它,因此每行每次都得到相同的结果。

def FindNodeLL(route_nodes):
        for node in route_nodes:
            try:
                response_xml = requests.get(f'https://api.openstreetmap.org/api/0.6/node/{node}')
                response_xml_as_string = response_xml.content
                responseXml = ET.fromstring(response_xml_as_string)
                for child in responseXml.iter('node'):
                    RouteNodeLL.append((float(child.attrib['lat']), float(child.attrib['lon'])))
                return RouteNodeLL
            except:
                pass

df[f'Route Nodes LL'] = df.apply(lambda row: FindNodeLL(row['Route Nodes']), axis = 1)
xwbd5t1u

xwbd5t1u1#

你只需要在完成任务后回来 for 循环并示例化您的 list 在职能范围内:

import pandas as pd
import requests
import xml.etree.ElementTree as ET

data = {
    "client": ["client a", "client b"],
    "nodes": [[1, 2, 10], [11, 12, 13]],
}

df = pd.DataFrame(data)

def FindNodeLL(route_nodes):
    RouteNodeLL = []
    for node in route_nodes:
        try:
            response_xml = requests.get(
                f"https://api.openstreetmap.org/api/0.6/node/{node}"
            )
            response_xml_as_string = response_xml.content
            responseXml = ET.fromstring(response_xml_as_string)
            for child in responseXml.iter("node"):
                RouteNodeLL.append(
                    (float(child.attrib["lat"]), float(child.attrib["lon"]))
                )
        except:
            pass
    return RouteNodeLL

df[f"Route Nodes LL"] = df["nodes"].apply(FindNodeLL)

相关问题