将csv文件加载到numpy并按名称访问列

时间:2014-06-10 14:37:40

标签: python arrays csv numpy

我有一个csv文件,标题如下:

鉴于此test.csv文件:

"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12

我只想将其加载为包含3行和7列的矩阵/ ndarray,并且我还希望从给定的column vectors访问column name。如果我使用genfromtxt(如下所示),我会得到一个包含3行(每行一行)且没有列的ndarray。

r = np.genfromtxt('test.csv',delimiter=',',dtype=None, names=True)
print r
print r.shape

[ (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291111964948.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291113113366.0)
 (611.88243, 9089.5601000000006, 5133.0, 864.07514000000003, 1715.3747599999999, 765.22776999999996, 1291120650486.0)]
(3,)

我可以从列名中获取列向量,如下所示:

print r['A']
  [ 611.88243  611.88243  611.88243]

如果,我使用load.txt,那么我将获得包含3行和7列的数组,但无法使用columns名称访问column(如下所示)。

numpy.loadtxt(open("test.csv","rb"),delimiter=",",skiprows=1)

我得到了

  [ [611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12]
    [611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12]
    [611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12] ]

Python中是否有任何方法可以同时实现这两个要求(access columns by coluumn name like np.genfromtext and have a matrix like np.loadtxt)?

2 个答案:

答案 0 :(得分:8)

单独使用numpy,您显示的选项是您唯一的选择。使用具有形状(3,7)的均匀d型的ndarray,或者(可能)异质dtype和形状(3,)的结构化阵列。

如果你真的想要一个带有标签列和形状(3,7)的数据结构(以及许多其他好东西)你可以使用 pandas DataFrame:

In [67]: import pandas as pd
In [68]: df = pd.read_csv('data'); df
Out[68]: 
           A          B     C          D           E          F     timestamp
0  611.88243  9089.5601  5133  864.07514  1715.37476  765.22777  1.291112e+12
1  611.88243  9089.5601  5133  864.07514  1715.37476  765.22777  1.291113e+12
2  611.88243  9089.5601  5133  864.07514  1715.37476  765.22777  1.291121e+12    

In [70]: df['A']
Out[70]: 
0    611.88243
1    611.88243
2    611.88243
Name: A, dtype: float64

In [71]: df.shape
Out[71]: (3, 7)

纯NumPy / Python替代方法是使用dict将列名映射到索引:

import numpy as np
import csv
with open(filename) as f:
    reader = csv.reader(f)
    columns = next(reader)
    colmap = dict(zip(columns, range(len(columns))))

arr = np.matrix(np.loadtxt(filename, delimiter=",", skiprows=1))
print(arr[:, colmap['A']])

产量

[[ 611.88243]
 [ 611.88243]
 [ 611.88243]]

这样,arr是一个NumPy矩阵,其列可以使用语法通过标签访问

arr[:, colmap[column_name]]

答案 1 :(得分:2)

因为您的数据是同构的 - 所有元素都是浮点值 - 您可以创建由genfromtxt返回的数据视图,该数据是2D数组。例如,

In [42]: r = np.genfromtxt("test.csv", delimiter=',', names=True)

创建一个"视图"的numpy数组; r。这是一个常规的numpy数组,但它是使用r

中的数据创建的
In [43]: a = r.view(np.float64).reshape(len(r), -1)

In [44]: a.shape
Out[44]: (3, 7)

In [45]: a[:, 0]
Out[45]: array([ 611.88243,  611.88243,  611.88243])

In [46]: r['A']
Out[46]: array([ 611.88243,  611.88243,  611.88243])

ra指的是同一块内存:

In [47]: a[0, 0] = -1

In [48]: r['A']
Out[48]: array([  -1.     ,  611.88243,  611.88243])