python - 应用函数未正确循环数据框中的列表
问题描述
我有一个看起来像下面的数据框
客户 | 节点 |
---|---|
客户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)
解决方案
您只需要在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)
推荐阅读
- javascript - 子弹跟随鼠标位置
- mysql - 两个查询单独工作,但是当我添加 OR 时结果变得无效
- pandas - 日内数据中的每日计算
- mysql - 如何将列基表转换为行基表
- python - 如何使用 PowerShell 使 python argcomplete 运行
- python-3.x - 在 Pyspark 中的 .withColumn 中编写自定义条件
- r - R shiny 中的级别替换创建两个级别列表,一个为 NULL
- typescript - 项目根目录中未引用的 .ts 文件“不在根目录下”
- mysql - 根据其他列中的数据更新列数据
- docker - Docker停止NPM脚本中的所有容器命令?