从csv文件中操作两个cols

时间:2017-05-06 17:00:07

标签: arrays python-2.7 csv

首先,让我告诉我,我花了近1个小时测试了很多可能的相关问题,但没有成功。这对我来说很复杂(初学者用户)。如果我按号码键入了号码,我会提前完成。但这个想法总是要学习。所以我想了解。

考虑以下示例:

>>> np.random.rand(3,2)
array([[ 0.14022471,  0.96360618],
       [ 0.37601032,  0.25528411],
       [ 0.49313049,  0.94909878]])

这是我需要与某些Voronoi代码一起使用的对象。但我的数据来自csv文件。

我有一个带标题的csv文件,我需要列clatclong。我想获得这样的输出:

array([[ clat_1,  clong_1],
       [ clat_2,  clong_2],
                ...
       [ clat_N,  clong_N]])

所以使用print输出将是这样的:

[[ 0.19151945  0.62210877]
 [ 0.43772774  0.78535858]
 [ 0.77997581  0.27259261]
 [ 0.39720258  0.78873014]
 [ 0.31683612  0.56809865]]

我用

加载了csv文件
csv_file='./demog.csv'
demog = np.genfromtxt(csv_file, delimiter=',', skip_header=0, skip_footer=0, names=True,dtype=None)

我尝试clat=demog['clat']clong=demog['clong']print clat看起来不是一列。

如何创建这样的N x 2对象(我甚至不知道它的名字:数组,列表,矩阵,表格......)

1 个答案:

答案 0 :(得分:1)

clat将为您提供整个lat列,clong将为您提供整个长列。要将它们放在像[lat,long]对中提到的数组中,您可以使用zip:

array = []

for lat, long in zip(clat, clong):
    array.append([lat, long])

array = np.array(array)
print array