gpt4 book ai didi

Python Matplotlib - 同一数据文件中的多个系列

转载 作者:行者123 更新时间:2023-11-28 22:38:46 25 4
gpt4 key购买 nike

我是 python 的“新手”(两周前开始学习),我正在尝试绘制一个如下所示的文件:

"1stSerie"    
2 23
4 12
6 12

"2ndSerie"
2 51
4 90
6 112

使用以下任何一种:pandas、matplotlib 和 numpy。但我并没有取得太大的成功。我尝试搜索示例,但没有一个适用于我的数据格式。

有人可以帮我找出如何将这个文件加载到 pandas 数据框中,或者(更好的是)告诉我如何绘制这个文件吗?

详细信息:

  • 对于我拥有的不同数据集,每个系列中的行数不同,但在同一数据集(文件)中,行数是相同的(如代码摘录中所示)。
  • 每个系列之间有一个空行,与代码摘录中完全一样。
  • 系列的标题是整个字符串,但是用一个词(如果使用两个词/列更容易导入)我可以更改标题。

更新 1:

在@Goyo 的帮助下,我将方法 convert() 更改为如下所示:

#!/usr/bin/env python3
def convert(in_file, out_file):
name = ""
for line in in_file:
line = line.strip()
print(line)
if line == "":
continue
if line.startswith('"'):
name = line.strip('"')
print("NAME:: " + name)
else:
out_file.write("{0}\n".format(','.join([name] + line.split("\t")) ) )

要绘制我使用以下代码:

with open('nro_caribou.dat') as in_file:
with open('output.txt', 'w+') as out_file:
convert(in_file, out_file)
df = pd.read_csv('output.txt', header=None,names=['Methods', 'Param', 'Time'], sep=",", )
print(df)
df.pivot(values='Time', index='Param', columns='Methods').plot()

我的原始数据:https://gist.github.com/pedro-stanaka/c3eda0aa2191950a8d83

还有我的情节:

the final chart

最佳答案

据我所知,pandas、matplotlib 或 numpy 中没有内置功能来读取这样的文件。如果您对数据格式有一些控制权,我鼓励您更改它。

如果您别无选择,只能使用该格式,您可以仅使用 python I/O 和字符串操作功能自行解析数据(我不认为 pandas 可以使这更容易,它不是为处理这些类型而设计的文件)。

此函数可以将数据从您的格式转换为另一种更适合 pandas 的格式:

def convert(in_file, out_file):
for line in in_file:
line = line.rstrip(' \n\r')
if not line:
continue
if line.startswith('"'):
name = line.strip('"')
else:
out_file.write('{}\n'.format(','.join([name] + line.split())))

如果您的原始文件是“input.txt”,您可以这样使用它:

with open('input.txt') as in_file:
with open('output.txt', 'w') as out_file:
convert(in_file, out_file)
df = pd.read_csv('output.txt', header=None,
names=['Series', 'X', 'Y'])
print(df)

Series X Y
0 1st Serie 2 23
1 1st Serie 4 12
2 1st Serie 6 12
3 2nd Serie 2 51
4 2nd Serie 4 90
5 2nd Serie 6 112

df.pivot(index='X', columns='Series', values='Y').plot()

enter image description here

关于Python Matplotlib - 同一数据文件中的多个系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35394803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com