【问题标题】:Function parameters iterate over a csv file values函数参数迭代 csv 文件值
【发布时间】:2022-01-08 03:57:12
【问题描述】:

我有这个功能

def audience(lat,lon,ids):
buff = buff_here(lat,lon)[-1]
count_visitas = []
for visitas in glob.glob(path): ......

df = pd.DataFrame(count_visitas, columns =['Visitas'])
df.to_csv(f'output/visitas_simi_{ids}.csv', index = False)
return count_visitas

由于工作问题,我无法在此处发布完整的代码,但如果我传递此参数,它就可以正常工作

audience(-33.51133739,-70.7558227,'CL0008')

现在,我有这个csv 并希望遍历 lat、lon 和 id 的行作为函数的参数。请问有什么帮助吗? :c

【问题讨论】:

  • 你是如何尝试从 csv 行传递变量的?
  • 是的,我想从 csv 行传递参数 lat, lon, ids :c

标签: python python-3.x pandas function csv


【解决方案1】:

您需要将 csv 与 csv.DictReader 一起引入,然后您可以调用所需的列:

csv_file = csv.DictReader(open(file, 'rU'))
for row in csv_file:
    count_visitas = audience(row['lat'],row['lon'],row['ids'])

【讨论】:

  • 谢谢!!完美运行,
  • 不客气。
【解决方案2】:

这段代码应该可以工作:

import csv

with open("names.csv", "r") as csv_file:
    csv_reader = csv.DictReader(csv_file)

    for line in csv_reader:
        lat = line["first_name"]
        lon = line["last_name"]
        ids = line["email"]

        audience(lat, lon, ids)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多