【问题标题】:Apply function not looping through list in dataframe correctly应用函数未正确循环数据框中的列表
【发布时间】:2021-07-09 14:22:46
【问题描述】:

我有一个如下所示的数据框

Client Nodes
Client A [32321,32312,2133432,43242,...]
Client 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)

【问题讨论】:

  • 请分享您的预期输出。
  • 这将是一个元组列表,例如 ((51.3232,-2.43432), (43.4324,-2.43243), (43.4343,-3.4343)...等)
  • 将其添加到您的原始问题中

标签: python pandas dataframe apply


【解决方案1】:

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

【讨论】:

  • 现在它只是返回列表中的一个元组 [(52.5797512, -2.0439439)] ,它似乎只是采用第一个节点并将函数应用于该节点。
  • 你确定其他节点都有效吗?当我使用您提供的数据时,这对我来说是个问题。
  • 我的代码返回 [(42.7957187, 13.5690032), (59.7717926, 30.32611), (14.2769353, -11.0519163)] 对于第一个示例(3 个有效节点)和 [] 作为第二个 [11, 12,13] 不是有效节点。
猜你喜欢
  • 1970-01-01
  • 2018-10-29
  • 2023-01-24
  • 2019-11-09
  • 1970-01-01
  • 2020-06-11
  • 2017-10-28
  • 2016-12-09
  • 2017-12-17
相关资源
最近更新 更多