首页 > 解决方案 > 将数据作为数组导入以在 Python 中绘图

问题描述

我对这个问题很陌生。我希望能从你的建议中受益。对不起,如果它是业余的。

我有以下代码,它最终显示了一个情节。我只写了一部分代码。

...
cov = np.dot(A, A.T)
samps2 = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
print(samps2)
names = ["x%s"%i for i in range(ndim)]
labels =  ["x_%s"%i for i in range(ndim)]
samples2 = MCSamples(samples=samps2,names = names, labels = labels, label='Second set')
g = plots.getSubplotPlotter()
g.triangle_plot([samples2], filled=True)

它没有问题。该图是使用来自 的数据绘制的samps2。要了解它samps2是什么,我们做print(samps2)并看看:

[[-0.11213986 -0.0582685 ]
 [ 0.20346731  0.25309022]
 [ 0.22737737  0.2250694 ]
 [-0.09544588 -0.12754274]
 [-1.05491483 -1.15432073]
 [-0.31340717 -0.36144749]
 [-0.99158936 -1.12785124]
 [-0.5218308  -0.59193326]
 [ 0.76552123  0.82138362]
 [ 0.65083618  0.70784292]]

我的问题是,如果我想从txt文件中读取这些数据。我应该怎么办?

谢谢你。

标签: pythonarrayspython-2.7importtext-files

解决方案


有几种方法。我想到的是:

普通蟒蛇:

data = []
with open(filename, 'r') as f:
    for line in f:
        data.append([float(num) for num in line.split()])

麻木:

import numpy as np
data = np.genfromtxt(filename, ...)

熊猫:

import pandas as pd
df = pd.read_table(filename, sep='\s+', header=None)

推荐阅读