2016-06-24 37 views
2

我有一个输入2个txt文件的程序。转换为浮点后,matplotlib输出不能将字符串转换为浮点数

deaths.txt

29.0 
122.0 
453.0 

years.txt

1995 
1996 
1997 

我做从

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

然后我转换列表为int数据和彩车名单

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) 

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

+0

你能转换列表,然后提供死亡和岁月的内容?我没有得到这些数组的错误:死亡= [“29.0”,“122.0”,“453.0”] 年= [“1995”,“1996”,“1997”] – Ohumeronen

+0

为什么你不转换最后元素,它是什么,你确定你想要绘制它(因为这就是你在做什么)? – Julien

+0

你也可以使用列表理解转换,或者甚至更好的'map' – Julien

回答

3

以下内容应该可以帮助您。而不是使用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() 

这将在屏幕上显示以下,显示出转换到整型和浮点是正确的:

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

而下面虎视眈眈则h会显示:

matplotlib graph

+0

我想通了。我喜欢你的方法。事情是,我没有转换最后一个字符,因为它是“”。该文件的最后一行。但我确实要求matplot lib来绘制它。那是错误发生的时候。我给它一个upvote,因为它非常有帮助。但它并没有解决我的问题。 –

+0

如果您试图处理缺失的数据,一种方法是使用'zip_longest'填充具有填充值的缺失条目。例如'0.0' –