寻求帮助从CSV文档中解压缩列。以下是我所包含的数据示例。
'local_time_rfc822', 'Wed, 24 Jan 2018 12:57:47 -0500'
'weather', 'Overcast'
'temperature_string', '30.2 F (-1.0 C)'
'wind_string', 'From the SE at 4.5 MPH Gusting to 6.9 MPH'
'latitude', '39.345784'
'longitude', '-83.23734'
使用以下方法产生行并返回“ValueError”,其中预期有6个值,但只找到2个。
import csv, json
from geojson import Feature, FeatureCollection, Point
features = []
with open('CurrentObs.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for local, weather, temp, wind, latitude, longitude in reader:
latitude, longitude = map(float, location.strip('()').split(','))
features.append(
Feature(
geometry = Point((latitude, longitude)),
properties = {
'local': local_time_rfc822,
'weather': weather,
'temp': temperature_string,
'wind': wind_string
}
)
)
collection = FeatureCollection(features)
with open("GeoObs.json", "w") as f:
f.write('%s' % collection)
谢谢!
答案 0 :(得分:0)
CSV文件中的每一行仅包含2
个值。它无法读取多行以满足您对6
值的解压缩。
相反,要加载该数据,您可以使用以下方法,它将以字典格式提供数据:
import csv
with open('CurrentObs.csv', newline='') as f_input:
data = dict(csv.reader(f_input, skipinitialspace=True, quotechar="'"))
print(data)
给你:
{'longitude': '-83.23734', 'temperature_string': '30.2 F (-1.0 C)', 'local_time_rfc822': 'Wed, 24 Jan 2018 12:57:47 -0500', 'wind_string': 'From the SE at 4.5 MPH Gusting to 6.9 MPH', 'weather': 'Overcast', 'latitude': '39.345784'}
因此data['longitude']
会为您提供字符串:-83.23734
或将其转换为浮点数:
data['longitude'] = float(data['longitude'])
它的工作原理是读取每行中的每对值,并以key
和value
格式构建字典。