加载csv到2D矩阵与numpy绘图 [英] load csv into 2D matrix with numpy for plotting

查看:225
本文介绍了加载csv到2D矩阵与numpy绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出此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列的矩阵/引号。但是,由于某些原因,我可以得到numpy是一个ndarray有3行(每行一个),没有列。

I simply want to load it as a matrix/ndarray with 3 rows and 7 columns. However, for some reason, all I can get out of numpy is an ndarray with 3 rows (one per line) and no columns.

r = np.genfromtxt(fname,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,)



我可以手动迭代, ,但这似乎很蠢。我只是想把它作为一个合适的矩阵加载,所以我可以分割它在不同的维度和绘图,就像在matlab。

I can manually iterate and hack it into the shape I want, but this seems silly. I just want to load it as a proper matrix so I can slice it across different dimensions and plot it, just like in matlab.

推荐答案

p>纯numpy

Pure numpy

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


检查 loadtxt 文档。

您也可以使用python的csv模组:

You can also use python's csv module:

import csv
import numpy
reader = csv.reader(open("test.csv", "rb"), delimiter=",")
x = list(reader)
result = numpy.array(x).astype("float")


将必须将其转换为您最喜欢的数字类型。我想你可以把整个事情写在一行:

You will have to convert it to your favorite numeric type. I guess you can write the whole thing in one line:


result = numpy.array(list(csv.reader(open("test.csv", "rb"), delimiter=","))).astype("float")

提示:

您也可以使用 pandas.io.parsers.read_csv code> numpy 可以更快的数组。

You could also use pandas.io.parsers.read_csv and get the associated numpy array which can be faster.

这篇关于加载csv到2D矩阵与numpy绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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