提取 csv 文件特定的列以在 Python 中列出 [英] Extract csv file specific columns to list in Python

查看:47
本文介绍了提取 csv 文件特定的列以在 Python 中列出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是使用 matplotlib、底图、python 等在地图上绘制特定风暴的纬度和经度值.我的问题是我试图提取纬度、经度和名称地图上的风暴,但我在第 41-44 行之间不断出现错误,我尝试将列提取到列表中.有人可以帮我解决这个问题.提前致谢.

What I'm trying to do is plot the latitude and longitude values of specific storms on a map using matplotlib,basemap,python, etc. My problem is that I'm trying to extract the latitude, longitude, and name of the storms on map but I keep getting errors between lines 41-44 where I try to extract the columns into the list. Could someone please help me figure this out. Thanks in advance.

文件如下:

1957,AUDREY,HU, 21.6N, 93.3W
1957,AUDREY,HU,22.0N,  93.4W
1957,AUDREY,HU,22.6N,  93.5W
1957,AUDREY,HU,23.2N,  93.6W

我希望列表如下所示:

latitude = [21.6N,22.0N,23.4N]
longitude = [93.3W, 93.5W,93.8W]
name = ["Audrey","Audrey"]

这是我目前所拥有的:

data = np.loadtxt('louisianastormb.csv',dtype=np.str,delimiter=',',skiprows=1)
'''print data'''

data = np.loadtxt('louisianastormb.csv',dtype=np.str,delimiter=',',skiprows=0)

f= open('louisianastormb.csv', 'rb')
reader = csv.reader(f, delimiter=',')
header = reader.next()
zipped = zip(*reader)

latitude = zipped[3]
longitude = zipped[4]
names = zipped[1]
x, y = m(longitude, latitude)

这是我收到的最后一条错误消息/回溯:

Here's the last error message/traceback I received:

回溯(最近一次调用最后一次):
文件/home/darealmzd/lstorms.py",第 42 行,

Traceback (most recent call last):
File "/home/darealmzd/lstorms.py", line 42, in

header = reader.next()
_csv.Error:在未加引号的字段中看到换行符 - 您是否需要以通用换行符模式打开文件?

header = reader.next()
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

推荐答案

这看起来像是代码中的行尾问题.如果您打算使用所有这些其他科学软件包,您也可以使用 Pandas 作为 CSV 阅读部分,它比 csv 模块更健壮、更有用:

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

如果您想要问题中的列表,您现在可以执行以下操作:

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

这篇关于提取 csv 文件特定的列以在 Python 中列出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆