python - 从迭代特定列中获取同一行
问题描述
如何在迭代特定列中从同一行添加添加列
加入-geo.csv 文件
title,place
Battle of Lade,Miletus
Battle of Mursa Major,Pannonia
Battle of Mursa Major,Osijek
这是我的代码
df = pd.read_csv('join-geo.csv')
with open('search_geo---' + str(timestr) + '.csv', 'w', encoding='utf-8') as output:
fieldnames = ['title','place', 'geoname']
output_writer = csv.DictWriter(output, delimiter=',', fieldnames=fieldnames)
output_writer.writeheader()
for i in df.place:
params = {'username': "xxx",
'name_equals': i,
'featureClass': ['P', 'A'],
'maxRows': "1"}
e = requests.get(url, params=params)
if e:
pretty_json = json.loads(e.text)
else:
print(f"{i} is unknown")
for item in pretty_json["geonames"]:
output_writer.writerow({'place': item['name'], 'geoname': "https://www.geonames.org/{}".format(item['geonameId'])})
它只是打印这样的东西
place,geoname
Miletus,https://www.geonames.org/4814762
Pannonia (Roman province),https://www.geonames.org/8181615
Osijek,https://www.geonames.org/3193935
我想要的是它也可以使用来自 df.place 的相同迭代打印标题列
我已经尝试过添加它
output_writer.writerow({'title': (a for a in df.title),'place': item['name'], 'geoname': "https://www.geonames.org/{}".format(item['geonameId'])})
,但事实证明它不在正确的路径/行中
预期输出:
title,place,geoname
Battle of Lade,Miletus,https://www.geonames.org/4814762
Battle of Mursa Major,Pannonia (Roman province),https://www.geonames.org/8181615
Battle of Mursa Major,Osijek,https://www.geonames.org/3193935
解决方案
推荐阅读
- c++ - 如何创建类类型列表,以便通过迭代重复调用模板函数?
- c# - 如何从另一个 aspx 页面获取事件控制。按钮点击或页面加载 | ASP.NET
- sharepoint - 使用 Node/SPFX 的 Sharepoint powershell cmdlet
- ocaml - 有没有办法优雅地拒绝在不受支持的操作系统上安装 opam 包?
- arrays - 快速排序中的循环条件
- css - 仅使用 TailwindCSS 将图像悬停在 div 内
- sql - 如何在 SQL Server 的另一个存储过程中执行存储过程?
- javascript - 如何一键提交两份表格?
- asp.net-web-api - 使用 .NET 5.0 构建天蓝色管道,警告?
- c - 使用 ?: 第一次用 C