首页 > 解决方案 > 从迭代特定列中获取同一行

问题描述

如何在迭代特定列中从同一行添加添加列

加入-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

标签: pythonpandasloopsdataframe

解决方案


推荐阅读