首页 > 解决方案 > 应用函数未正确循环数据框中的列表

问题描述

我有一个看起来像下面的数据框

客户 节点
客户A [32321,32312,2133432,43242,...]
客户 B [575945,545345,54353,5345,...]

我正在尝试使用apply函数循环遍历每个客户端列表中的每个项目并在每个数字上运行该函数,因此首先对客户端A使用32321然后使用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)

标签: pythonpandasdataframeapply

解决方案


您只需要在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)

推荐阅读