2016-06-24 8 views
2

2つのtxtファイルを入力するプログラムがあります。floatに変換した後、matplotlibの出力は文字列をfloatに変換できません

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

あなたが死亡し、数年のコンテンツを提供することができますか?私はこれらの配列にエラーはありません:deaths = ["29.0"、 "122.0"、 "453.0"] 年= ["1995"、 "1996"、 "1997"] – Ohumeronen

+0

なぜあなたは最後の要素は何ですか、それは何ですか、あなたはそれをプロットしてもよろしいですか(これはあなたがやっていることなので)? – Julien

+0

また、リスト内包表記を使って変換することができます。より良い 'map' – Julien

答えて

3

次のようにしてください。 readlines()を使用してファイル全体を読み取るのではなく、読み込まれた各行を変換する方が良いでしょう。

2つのデータファイルの要素数が異なるため、コードでは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() 

これは、int型と浮動小数点数への変換が正しかったことを示し、画面に次のように表示されます

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

そして次GRAP時間は、表示されます:あなたはリストを変換する前に

matplotlib graph

+0

私はそれを理解しました。私はあなたに近づきます。事は ""だったので最後の文字を変換しなかったということでした。ファイルの最後の行。しかし、私はmatplot libにそれをプロットするように依頼しました。そしてそれはエラーが来た時です。それは非常に有用だったので、私はupvoteを与えた。しかし、それは私の問題を解決しませんでした。 –

+0

欠けているデータに対処しようとしている場合、1つの方法は、 'zip_longest'を使用して、不足している項目を塗りつぶし値で補うことです。たとえば、「0.0」 –

関連する問題