python - 转换为 float 后,matplotlib 输出无法将字符串转换为 float

标签 python python-3.x matplotlib

我有一个输入 2 个 txt 文件的程序。

死亡.txt

29.0
122.0
453.0

年.txt

1995
1996
1997

我根据数据制作 list

deaths = open("deaths.txt").read().splitlines()
years = open("years.txt").read().splitlines()

然后我将列表转换为 int 和 float

for x in years[:-1]:
    x = int(x)

for x in deaths[:-1]:
    x = float(x)

然后是它给出错误的部分:ValueError: could not convert string to float

plt.plot(years, deaths)

所以它说它不能将字符串转换为 float 。但我想我已经做到了。可能是什么原因?

最佳答案

以下内容应该可以让您继续前进。与其使用 readlines() 读取整个文件,更好的方法是在读入时转换每一行。

由于您的两个数据文件具有不同数量的元素,因此代码使用了 zip_longest0.0 填充任何缺失的死亡数据:

from itertools import zip_longest
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

with open('deaths.txt') as f_deaths:
    deaths = [float(row) for row in f_deaths]

with open('years.txt') as f_years:
    years = [int(row) for row in f_years]

# Add these to deal with missing data in your files, (see Q before edit)    
years_deaths = list(zip_longest(years, deaths, fillvalue=0.0))
years = [y for y, d in years_deaths]
deaths = [d for y, d in years_deaths]

print(deaths)
print(years)

plt.xlabel('Year')
plt.ylabel('Deaths')

ax = plt.gca()
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%d'))
ax.set_xticks(years)

plt.plot(years, deaths)
plt.show()

这将在屏幕上显示以下内容,表明到整数和 float 的转换是正确的:

[29.0, 122.0, 453.0, 0.0]
[1995, 1996, 1997, 1998]    

然后会显示下图:

matplotlib graph

关于python - 转换为 float 后,matplotlib 输出无法将字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38008774/

相关文章:

python - 无法安装 Python 包 [SSL : TLSV1_ALERT_PROTOCOL_VERSION]

python - 检查符号和大写/小写以使用凯撒密码进行加密?

audio - 在 Python 3 中读取 ID3 标签

python - 如何循环遍历集合,同时从 Python 3 中的集合中删除项目

python - 如何在 matplotlib 图形文本中使用(新样式)字符串格式

python - 删除 matplotlib 图中的空子图

python - 更改 matplotlib 中错误栏的 capstyle

python - Django 多处理异常

python - plotly.graph_objects.table 静态表

python - 属性错误 : 'NoneType' object has no attribute '_meta'