csvファイルの行毎の最大値がその行の2番目に大きい値の2倍を超える行に限り、その行の要素(Name,最大値が存在数る列の要素(One~Five),最大値)を表示した上で、新規作成したcsvファイルに該当する行の全ての要素を書き込むようなコードを書こうとした際、以下のエラーが出ました。
下記のような出力結果を得る為にお知恵をお貸しいただけますと幸いです。宜しくお願いします。
理想の出力結果
#ターミナル上の出力 [A,"Three",14] [C,"Three",12] [D,"Four",14] [E,"Four",12] [F,"One",10] #作成するcsvファイルの中身 Name,One,Two,Three,Four,Five A,3,3,14,4,2 C,3,2,12,4,3 D,2,4,5,14,6 E,4,3,5,12,4 F,10,2,3,4,2
エラー
Traceback (most recent call last): File "/Users/macuser/.pyenv/versions/3.7.4/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2897, in get_loc return self._engine.get_loc(key) File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: ('A', 'Three', 14) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "zoki.py", line 14, in <module> df2 = df[idx, score.index[0], score[0]] File "/Users/macuser/.pyenv/versions/3.7.4/lib/python3.7/site-packages/pandas/core/frame.py", line 2980, in __getitem__ indexer = self.columns.get_loc(key) File "/Users/macuser/.pyenv/versions/3.7.4/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 2899, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: ('A', 'Three', 14)
コード
comp2.py
1import pandas as pd 2df = pd.read_csv('renshu.csv', index_col='Name') 3for idx, row in df.iterrows(): 4 score = row['One':'Five'].sort_values(ascending=False) 5 df2 = df[idx, score.index[0], score[0]] 6 df3 = df[score.iloc[0] >= score.iloc[1] * 2] 7 print(df2) 8 df3.to_csv("score.csv")
ファイル
renshu.py
1Name,One,Two,Three,Four,Five 2A,3,3,14,4,2 3B,3,8,2,4,5 4C,3,2,12,4,3 5D,2,4,5,14,6 6E,4,3,5,12,4 7F,10,2,3,4,2
補足情報(FW/ツールのバージョンなど)
iOS 10.14.6, Python 3.7.4, Atom
回答4件
あなたの回答
tips
プレビュー