我有一个输入 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_longest
用 0.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]
然后会显示下图:
关于python - 转换为 float 后,matplotlib 输出无法将字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38008774/