前提・実現したいこと
初心者です。初めて投稿するため、記載に不足があったら教えていただけると助かります。
以下のエラー回避方法、または他のデータ処理方法があれば教えていただきたいです。
csvファイルのなかで、
上下の列の値を比較し、
値が同じならば上の行を削除
というプログラムを書きたいと考えています。
以下を参考にプログラムを作成しました。
pandas.DataFrameの任意の位置のデータを選択し処理
https://note.nkmk.me/python-pandas-at-iat-loc-iloc/
特定の行を削除する
https://pythondatascience.plavox.info/pandas/%E8%A1%8C%E3%83%BB%E5%88%97%E3%82%92%E5%89%8A%E9%99%A4
データ例(テストデータでは、500行分のデータを使用しています)
data_id floor
0 1 6
1 2 8
2 3 9
3 4 3
4 5 2
5 6 6
6 7 6
7 8 3
8 9 8
9 10 4
10 11 6
11 12 0
12 13 0
13 14 5
14 15 9
15 16 7
16 17 5
17 18 3
18 19 9
19 20 7
20 21 -1
21 22 7
22 23 8
23 24 0
24 25 2
25 26 4
26 27 1
27 28 3
28 29 8
29 30 7
.. ... ...
以下のコードで処理を実行しようとしました。
Python
1import pandas as pd 2 3#データ読み込み 4filename="data_test.csv" 5df = pd.read_csv(filename, engine='python') 6 7for i in range(len(df)): 8 if df.iat[i,1] == df.iat[i-1,1]: 9 print(df.iat[i,0], df.iat[i,1]) 10 df.drop(i-1,inplace=True)
発生している問題・エラーメッセージ
以下エラーが発生します。
データフレームの長さをrangeに入れているのに対して、処理実行により処理後のデータフレームの長さが短くなっているからか?と考えていますが回避方法がわからないため、質問させていただきました。
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-22-2d387042cd5b> in <module>() 8 9 for i in range(len(df)): ---> 10 if df.iat[i,1] == df.iat[i-1,1]: 11 print(df.iat[i,0], df.iat[i,1]) 12 df.drop(i-1,inplace=True) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key) 2140 2141 key = self._convert_key(key) -> 2142 return self.obj._get_value(*key, takeable=self._takeable) 2143 2144 def __setitem__(self, key, value): ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in _get_value(self, index, col, takeable) 2531 if takeable: 2532 series = self._iget_item_cache(col) -> 2533 return com._maybe_box_datetimelike(series._values[index]) 2534 2535 series = self._get_item_cache(col) IndexError: index 463 is out of bounds for axis 0 with size 463
補足情報
他の列削除方法がもしあれば教えていただきたいです。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/12/04 09:09
2018/12/04 10:33
2018/12/05 08:44