2012-06-20 75 views
4

Python新手入门(以及一般编程),如果这很简单并且/或者在某处我没有找到答案,请随时以典型的论坛方式骚扰我。阅读CSV并按列分开

我有一大堆的CSV,每个都包含10 XY坐标这样的:

10,5 
2,4 
5,6 
7,8 
9,12 
3,45 
2,4 
6,5 
0,3 
5,6 

我期待的X坐标和Y坐标分成两个单独列出,这样我就可以减来自给定列表中每个值的值。例如,从X坐标列表中的每个值中减去5,并从Y坐标列表中的每个值中减去3。然后,我将采取每个值的abs()并找到最小值。一旦这些最小值被发现,我想将名单加在一起,使每个值添加到它的对应

IE)如果X的绝对值是像

4 
5 
.... 

和Y类似

6 
7 
.... 

我要添加4和6,然后5和7,等等

将它们分开,我试图

import csv 
filein = open("/path/here") 
reader = csv.reader(filein, skipinitialspace = True) 
listofxys = [] 
for row in reader: 
    listofxys.append(row) 

Xs = listofxys.pop(0) # to pop all the X's 

Ys = listofxys.pop() # to pop all the Y's 

但不是所有的主要值,它提供了第一个XY对。我在这里做错了什么?

最终的目标是找到最接近XY坐标的点,所以如果这是一个不好的方法去做,可以随意引导我到另一个方向。

在此先感谢!

回答

5

值得注意的是,在Python中打开文件时,应该尝试使用 the with statement 。这样更具可读性,并且可以消除文件未被关闭的可能性(即使发生异常时也是如此)。

你的实际问题在于你没有做你想做的事情。

reader = csv.reader(filein, skipinitialspace = True) 
listofxys = [] 
for row in reader: 
    listofxys.append(row) 

所有这些都是以非常低效的方式使用reader = list(csv.reader(filein, skipinitialspace = True))

你想要做的就是使用the zip() builtin来取对的列表并将它变成两个列表。你这样做与明星运营商:

import csv 

with open("test") as filein: 
    reader = csv.reader(filein, skipinitialspace = True) 
    xs, ys = zip(*reader) 

print(xs) 
print(ys) 

其中给出:

('10', '2', '5', '7', '9', '3', '2', '6', '0', '5') 
('5', '4', '6', '8', '12', '45', '4', '5', '3', '6') 

请注意,其实这些值都是字符串。如果你想让他们成为数字,你会想要使用csv.QUOTE_NONNUMERIC,例如。G:reader = csv.reader(filein, quoting=csv.QUOTE_NONNUMERIC, skipinitialspace = True)

其中给出:

(10.0, 2.0, 5.0, 7.0, 9.0, 3.0, 2.0, 6.0, 0.0, 5.0) 
(5.0, 4.0, 6.0, 8.0, 12.0, 45.0, 4.0, 5.0, 3.0, 6.0) 
1
import os,csv, numpy, scipy 
    from numpy import * 
    f= open('some.csv', 'rb') 
    reader = csv.reader(f, delimiter=',') 
    header = reader.next() 
    zipped = zip(*reader) 
    print(zipped[1]) # is the 2nd column of the csv file 

HTH