python - 如何用Python绘制结构化数据文件?

标签 python numpy pandas matplotlib

我有一个具有以下结构的数据文件:

cat data.dat
%        1
0.9  0.9  0.6  0.5
0.0  0.1  0.3  0.2 
0.5  0.2  0.0  0.1
%        2
0.2  0.6  0.2  0.3
0.2  0.1  0.1  0.2 
0.4  0.2  0.1  0.1

我只是展示了一个简单的例子,只有 2 组数据,但文件 比这个大得多。我想要的是读取文件 Python,然后告诉 Python 计算以 % 2 开头的集合 如下。从这个集合中,我想绘制 row=1 w.r.t.这 在本例中,整数数组为 1,2,3,4。

我可以用 GNUPLOT 来做到这一点,但我花了很多时间,因为首先我需要 剪切我想要的集合并将其粘贴到临时文件中。其次,我使用AWK 转置矩阵。

我想知道我的建议在 Python 中是否可行。

谢谢。

最佳答案

好吧,如果您需要从文件中访问各种数据(考虑 @gboffi post ,则有一个限制,即设置标签按连续顺序排列):

from matplotlib import pyplot as plt

data = []

with open('cat_data.dat') as f:
    for line in f:
        if line[1].isalpha():
            continue
        if line.startswith('%'):
            data.append([])
            continue
        data[-1].append([float(x) for x in line.split()])

# Now you have all values in data:
# [[[0.9, 0.9, 0.6, 0.5], [0.0, 0.1, 0.3, 0.2], [0.5, 0.2, 0.0, 0.1]], [[0.2, 0.6, 0.2, 0.3], [0.2, 0.1, 0.1, 0.2], [0.4, 0.2, 0.1, 0.1]]]

_set = 2
row = 1 # Corresponds to 0.2  0.1  0.1  0.2

plt.plot(range(1, 5), data[_set - 1][row])
plt.show()

enter image description here

关于python - 如何用Python绘制结构化数据文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37416026/

相关文章:

python - python中FFT的循环加速(使用 `np.einsum`)

python - 组合两个数组而不重复

python - 仅将列表中的项目保留在包含某些字符的数据框中

python - 描述Python Pandas模块中的函数

网格图像基本 FFT 的 Python 代码

python - 在 Python 3.3 中使用 %s 的 SQL 查询

python - scipy.sparse 函数会释放 GIL 吗?

python - pandas 替换行和列子集的空值

python - 选择除 BeautifulSoup 中具有某些类的所有 div

c++ - 为嵌入式解释器安装为 VS2010 编译的 Numpy