【问题标题】:Convert string from text file inorder to plot using matplotlib将字符串从文本文件转换为使用 matplotlib 绘图
【发布时间】:2016-08-11 20:33:52
【问题描述】:

我正在尝试使用文本文件中的日期和整数绘制图表,如下所示:

但我不断收到此错误

回溯(最近一次通话最后一次):
文件“C:\Users\Haeshan\Desktop\Comp Sci CC\graph.py”,第 21 行,在 图()
文件“C:\Users\Haeshan\Desktop\Comp Sci CC\graph.py”,第 9 行,在图中 转换器 = {1: mdates.strpdate2num("%d/%m/%Y")})
文件“C:\Users\Haeshan\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\npyio.py”,第 930 行,在 loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)] 文件“C:\Users\Haeshan\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\npyio.py”,第 930 行,在
items = [conv(val) for (conv, val) in zip(converters, vals)]
文件“C:\Users\Haeshan\AppData\Local\Programs\Python\Python35\lib\site-packages\numpy\lib\npyio.py”,第 659 行,在 floatconv
返回浮点数(x)
ValueError:无法将字符串转换为浮点数:b“['10'”

import matplotlib.pyplot as plt
import numpy as np
import csv
import matplotlib.dates as mdates

def graph():
    date, value = np.loadtxt("Scores.txt", delimiter = ",", unpack=True,
                             converters = {1: mdates.strpdate2num("%d/%m/%Y")})
    fig = plt.figure()
    ax1 = fig.add_subplot(1,1,1, axisbg ="white")
    plt.plot_date(x=date, y=value)
    plt.title("Performace")
    plt.ylabel("Score")
    plt.xlabel("Date")
graph()

任何想法, 非常感谢

【问题讨论】:

  • 因为date 是一个字符串...如果第一列说10 而不是['10'] 就可以了。 loadtxt 不知道要去掉括号和引号以将 '10' 解析为 int 10

标签: python-3.x matplotlib graph error-handling


【解决方案1】:

问题是您的第一列有引号。既然你无论如何定义了转换器,我会把它改成

converters = {0: (lambda x: int(x)),1: mdates.strpdate2num("%d/%m/%Y")})

更新

抱歉,由于引号,我没有看到其他问题。 TBH,在这种情况下,我不会使用np.loadtxt,因为您在每行中也有方括号。此外,您还有一个问题,您正在使用 Python 3,其中字符串是 unicode 而不是字节,但 loadtxt 将用于字节(因此 b 在您的行前面)。 我的建议是逐行阅读并解析每一行,例如

dates,values = list(),list()
formater = mdates.strpdate2num("%d/%m/%Y")
with open("Scores.txt",'r',newline='\n') as input_file:
    for line in input_file:
        # Remove the square brackets, quotation marks and newlines (if necessary)
        # Be aware that this will also kill all square brackets and quotations marks in your line
        entries = line.replace('[','').replace(']','').replace("'",'').replace('\n','').split(',')
        values.append(int(entries[0]))
        dates.append(formater(entries[1]))

【讨论】:

  • 遗憾的是仍然给出了一个错误但不同的 ValueError: invalid literal for int() with base 10: b"['10'"
  • 您好,感谢您的更新,我使用了您的示例,但弹出了此示例。 “C:\Users\Haeshan\AppData\Local\Programs\Python\Python35\lib_strptime.py”,第 346 行,在 _strptime data_string[found.end():]) ValueError:未转换的数据仍然存在:
  • 文本文件的格式也会引发错误。当我将列表附加到文本文件时,分数(整数)和日期之间有一个空格,如原始帖子中所附图像所示。但是现在它提出了这一点。 dates.append(formater(entries[1])) ValueError: 时间数据 '12/08/2016\r' 与格式 '%d/%m/%Y' 不匹配
  • 由于您在 Windows 上工作,您还必须像我对 '\n' 所做的那样删除 '\r' ...或者您可以直接在使用 '%d/%m/%Y\r' 而不是 '%d/%m/%Y' 的格式化程序(但这是一个相当难以理解的 hack TMO)
  • 我添加了一些替换。条目 = line.replace('[','').replace(']','').replace("'",'').replace('\r','').replace('\n ','').split(',') 但是同样的错误出现了。 ValueError: 时间数据 '12/08/2016' 与格式 '%d/%m/%Y' 不匹配,但它们不是相同的格式吗?
猜你喜欢
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
相关资源
最近更新 更多