我有一个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
)?
答案 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])
r
和a
指的是同一块内存:
In [47]: a[0, 0] = -1
In [48]: r['A']
Out[48]: array([ -1. , 611.88243, 611.88243])