gpt4 book ai didi

python - 如何在python中从文件中提取数据

转载 作者:行者123 更新时间:2023-12-03 21:54:14 24 4
gpt4 key购买 nike

如何在多线图中绘制这些数据?

我曾尝试使用这些代码,但只有每行的第一个值被添加到列表中

对于我的 y 轴,我想得到设备的值乘以 0.5,0,1,0 的值(例如对于第 1 行,(电视值 = 120)我应该得到 24 个图,它们位于

y 轴:60 和
x 轴 0

y 轴 0 和
x 轴 1

y 轴 120 和
x 轴 2

等等......总共有 24 个图(我的 y 标签将由 0 到 2200 的值组成)

对于我的 x 轴,我将绘制 x_labels 的值

文件格式

Residents: 4
TV1:120:0.5,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0.5,0,0,0.5,1,1,1,0.5
Computer:320:1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Fridge1:250:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Dishwasher:500:0.5,1,1,0.5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1
Blender:700:0,0,0,0,0,0,0,0,0,0,0,0,0,0.05,0,0,0,0,0,0,0,0,0,0
Fridge2:50:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Coffee machine:2400:0,0,0,0,0,0,0,0,0,0.05,0.05,0,0,0,0,0,0,0,0,0,0,0,0,0
Kettle:2200:0.05,0,0,0,0,1,0,0,0.05,0,0.05,0.05,0,0,0,0,0.05,0,0,0,0,0.05,0.05,0
Freezer:140:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Slow cooker:300:0,0,0,0,0,0,0,0,0,0,0,0,0.5,1,1,1,1,1,0.5,0,0,0,0,0

我的代码
import matplotlib.pyplot as plt
import numpy as np

x = []
y = []

x_labels = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23']

fileobj = open('file.csv','r')
for line in fileobj:
line_s = line.strip()
Usage = [(x) for x in line_s.split(',')]
y.append(Usage[2])




fileobj.close()

plt.plot(y ,"o--")
plt.ylabel("usage")
plt.xlabel("time")
plt.show()

最佳答案

import matplotlib.pyplot as plt
import numpy as np

x_labels = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23']

with open(r'C:\Users\$env:UserName\Desktop\MyScripts\file.csv', 'r') as file_obj:
for line in file_obj:
line = line.strip('\n')
# print(f"{line = }")
usage = [x for x in line.split(',')]
# print(f"{usage = }")
number = float(usage[0].split(':')[1])
first = [float(usage[0].split(':')[-1])]
remaining = [float(x) for x in usage[1:]]
# print(f"{first = }")
# print(f"{type(first) = }")
# print(f"{remaining = }")
first.extend(remaining) # * number
res = list(map(lambda x: x * number, first))
print(f"{res = }")

plt.plot(res, "o--")
plt.ylabel("usage")
plt.xlabel("time")
plt.show()
enter image description here

关于python - 如何在python中从文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62063331/

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