0

CSVファイルをpandasで読み込んでリストの作成と平均のまとめを行った結果、エラーになってしまい、ファイルに原因があるのか、コードに原因があるのかが分かりません。
解決策があればご意見、よろしくお願いします。

コード

import pandas as pd

# pandasでcsvを読み込む
df = pd.read_csv("kion10y.csv", encoding="utf-8")

# 日付ごとに気温をリストにまとめる
md = {}
for i, row in df.iterrows():
    m,  d,v = (int(row['月']), int(row['日']), float(row['気温']))
    key = str(m) + "/" + str(d)
    if not(key in md): md[key] = []
    md[key] += [v]

# 日付ごとに平均を求める
avs = {}
for key in md:
    v = avs[key] = sum(md[key]) / len(md[key])
    print("{0} : {1}".format(key,v))

エラーメッセージ

Traceback (most recent call last):
  File "/Users/fujiokamasaya/Desktop/python.test/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 4411, in get_value
    return libindex.get_value_at(s, key)
  File "pandas/_libs/index.pyx", line 44, in pandas._libs.index.get_value_at
  File "pandas/_libs/index.pyx", line 45, in pandas._libs.index.get_value_at
  File "pandas/_libs/util.pxd", line 98, in pandas._libs.util.get_value_at
  File "pandas/_libs/util.pxd", line 83, in pandas._libs.util.validate_indexer
TypeError: 'str' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/fujiokamasaya/PycharmProjects/project/tenki.1.py", line 10, in <module>
    m,  d,v = (int(row['月']), int(row['日']), float(row['気温']))
  File "/Users/fujiokamasaya/Desktop/python.test/lib/python3.7/site-packages/pandas/core/series.py", line 871, in __getitem__
    result = self.index.get_value(self, key)
  File "/Users/fujiokamasaya/Desktop/python.test/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 4419, in get_value
    raise e1
  File "/Users/fujiokamasaya/Desktop/python.test/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 4405, in get_value
    return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
  File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 90, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1618, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1626, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: '月'

CSVファイルの内容

年, 月, 日, 気温, 品質, 均質, 
2010,1,5,7.4,8,1
2010,1,6,4.6,8,1
2010,1,7,4.5,8,1
2010,1,8,5.5,8,1
2010,1,9,5.8,8,1
2010,1,10,7.3,8,1
2010,1,11,7.0,8,1
2010,1,12,6.8,8,1
2010,1,13,2.5,8,1
2010,1,14,2.3,8,1
2010,1,15,4.6,8,1
2010,1,16,3.9,8,1
2010,1,17,3.9,8,1
2010,1,18,5.4,8,1
2010,1,19,7.9,8,1
2010,1,20,9.9,8,1
2010,1,21,10.3,8,1
2010,1,22,6.5,8,1
5
  • CSVファイルもエラーの可能性として考えられるのであれば、実際に使用しているデータを質問文に含めておくと回答が得られやすくなると思います。
    – cubick
    2020年2月23日 16:47
  • dfをprintで出力した結果が、以下になります。 年 月 日 気温 品質 均質 0 2010 1 5 7.4 8 1 NaN 1 2010 1 6 4.6 8 1 NaN 2 2010 1 7 4.5 8 1 NaN 3 2010 1 8 5.5 8 1 NaN 4 2010 1 9 5.8 8 1 NaN ... ... .. .. ... ... ... .. 3644 2019 12 28 7.3 8 1 NaN 3645 2019 12 29 8.4 8 1 NaN 3646 2019 12 30 9.7 8 1 NaN 3647 2019 12 31 9.5 8 1 NaN 3648 2020 1 1 6.9 8 1 NaN [3649 rows x 7 columns] プロセスは終了コード 0 で完了しました
    – TORA
    2020年2月23日 22:46
  • 1
    CSVファイルを読み込む際に skipinitialspace=True を指定するとよろしいかと思います。, df = pd.read_csv("kion10y.csv", encoding="utf-8", skipinitialspace=True)
    – user39889
    2020年2月23日 23:50
  • 1
    ちなみにですが、平均気温は df.groupby(['年', '月', '日'])['気温'].mean() としても求める事が可能です。
    – user39889
    2020年2月24日 1:03
  • ありがとうございます!
    – TORA
    2020年2月24日 9:17

2 件の回答 2

1

ファイルに原因があるのではないかと予想されます。
csvにカラムがあるかご確認ください。

@metropolis さんのコメントの通り、csvのヘッダにスペースが入っているのが原因のようです。
公式ドキュメント(英語)解説ブログを参考にskipinitialspaceを有効にしてください。

うまく行くcsv
月,日,気温
1,2,3
1,2,6
# 1/2 : 4.5
同様のエラーになるcsvその1
すっぽん,日,気温
1,2,3
1,2,6
同様のエラーになるcsvその2
 月, 日, 気温
1,2,3
1,2,6
検証コード
import pandas as pd

# エラーになる
#df = pd.read_csv("kion10y.csv", encoding="utf-8")
# エラーにならない
df = pd.read_csv("kion10y.csv", encoding="utf-8", skipinitialspace=True)

md = {}
for i, row in df.iterrows():
    m, d,v = (int(row['月']), int(row['日']), float(row['気温']))
    key = str(m) + "/" + str(d)
    if not(key in md):
       md[key] = []
    md[key] += [v]

avs = {}
for key in md:
    v = avs[key] = sum(md[key]) / len(md[key])
    print("{0} : {1}".format(key,v))
3
  • ファイル内容です。 年, 月, 日, 気温, 品質, 均質, 2010,1,5,7.4,8,1 2010,1,6,4.6,8,1 2010,1,7,4.5,8,1 2010,1,8,5.5,8,1 2010,1,9,5.8,8,1 2010,1,10,7.3,8,1 2010,1,11,7.0,8,1 2010,1,12,6.8,8,1 2010,1,13,2.5,8,1 2010,1,14,2.3,8,1 2010,1,15,4.6,8,1 2010,1,16,3.9,8,1 2010,1,17,3.9,8,1 2010,1,18,5.4,8,1 2010,1,19,7.9,8,1 2010,1,20,9.9,8,1 2010,1,21,10.3,8,1 2010,1,22,6.5,8,1
    – TORA
    2020年2月23日 22:50
  • 検証コードを実行した結果、同様にエラーになりました。
    – TORA
    2020年2月23日 22:52
  • コードと説明文を変更しました。再度ご確認ください。
    – payaneco
    2020年2月24日 6:12
0

ヘッダの月から均質まで、前にスペースが入ってます。

年, 月, 日, 気温, 品質, 均質, 

スペースを削除してみてください。

年,月,日,気温,品質,均質,
1
  • スペースが入っている事に気付きませんでした。。。スペースを削除して再実行したら無事、完了しました!!ありがとうございます!!
    – TORA
    2020年2月24日 9:18

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。