【问题标题】:Importing data as an array for plotting in Python将数据作为数组导入以在 Python 中绘图
【发布时间】:2018-10-10 22:05:52
【问题描述】:

我是这个问题的新手。我希望能从你的建议中受益。如果是业余的,请见谅。

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

...
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 文件中读取这些数据。我该怎么办?

谢谢。

【问题讨论】:

    标签: python arrays python-2.7 import text-files


    【解决方案1】:

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

    普通蟒蛇:

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

    numpy:

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

    熊猫:

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

    【讨论】:

    • 非常感谢我的朋友的完整回答。我不知道为什么,但只是 numpy 工作。
    • 不客气。我认为这三个非常相似,除了 pandas 使用数据帧而不是普通数组,但仍然:我不知道您所说的 not 工作是什么意思,所以也许您的方法出于某种原因只适合numpy 数组,但不是列表或数据框。
    猜你喜欢
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    相关资源
    最近更新 更多