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

标签 python file

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

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

对于我的 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/

相关文章:

ruby - 将文件中的字节数据读入多个整数

Silverlight 4 RC 文件上传,上传进度为 : how to?

file - 代码点火器 "file_exists($filename)"

python - 每个重试周期增加 celery 重试时间

python - 运行 Python 脚本, 'Memory error', 'for' 循环

java - 在 try catch block 之外使用变量 (Java)

c - 读取 C 中的新行

python - 检测无限递归

python - 无法提供图表作为 youtube 搜索 API 的参数

python 脚本一直使用 120% CPU