[英]How do I write a for loop within a function to pickup values within a csv?
我有一個名為sampleweather100的文件,其中包含地址的緯度和經度。 如果我在位置列表功能下手動輸入這些緯度和經度,則會得到我想要的輸出。 但是,我想編寫一個函數,以在不手動輸入的情況下為csv的所有行提取輸出:
import pandas as pd
my_cities = pd.read_csv('sampleweather100.csv')
from wwo_hist import retrieve_hist_data
#lat = -31.967819
#lng = 115.87718
#location_list = ["-31.967819,115.87718"]
frequency=24
start_date = '11-JAN-2018'
end_date = '11-JAN-2019'
api_key = 'MyKey'
location_list = ["('sampleweather100.csv')['Lat'],('sampleweather100.csv')['Long']"]
hist_weather_data = retrieve_hist_data(api_key,
location_list,
start_date,
end_date,
frequency,
location_label = False,
export_csv = True,
store_df = True)
我的函數location_list = ["('sampleweather100.csv')['Lat'],('sampleweather100.csv')['Long']"]
不起作用。 是否有更好的方法或forloop可以將經緯度較長的每一行提取到該location_list
函數中:
數據集代表:
my_cities
Out[89]:
City Lat Long
0 Lancaster 39.754545 -82.636371
1 Canton 40.851178 -81.470345
2 Edison 40.539561 -74.336307
3 East Walpole 42.160667 -71.213680
4 Dayton 39.270486 -119.577078
5 Fort Wainwright 64.825343 -147.673877
6 Crystal 45.056106 -93.350020
7 Medford 42.338916 -122.839771
8 Spring Valley 41.103816 -74.045399
9 Hillsdale 41.000879 -74.026089
10 Newyork 40.808582 -73.951553
您建立列表的方式沒有任何意義。 您正在使用csv的文件名,它只是一個字符串,不包含對文件本身或從中創建的數據框的引用。
由於使用pandas
從csv中構建了一個名為my_cities的數據my_cities
,因此需要從my_cities
數據my_cities
提取成對列表:
location_list = [','.join([str(lat), str(lon)]) for lat, lon in zip(my_cities['Lat'], my_cities['Long'])]
這是使用示例數據框從上一行獲得的列表:
['39.754545,-82.636371', '40.851178000000004,-81.470345',
'40.539561,-74.33630699999999', '42.160667,-71.21368000000001',
'39.270486,-119.577078', '64.825343,-147.673877', '45.056106,-93.35002',
'42.338916,-122.839771', '41.103815999999995,-74.045399',
'41.000879,-74.026089', '40.808582,-73.951553']
您可以使用以下方法之一將數據幀轉換為逗號分隔的對列表:
location_list = [
'{},{}'.format(lat, lon)
for i, (lat, lon) in my_cities.iterrows()
]
要么
location_list = [
'{},{}'.format(lat, lon)
for lat, lon in my_cities.values
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.