1 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
您應(yīng)該避免在迭代列表時(shí)修改列表。而是創(chuàng)建一個(gè)索引列表以刪除它們,然后在您找到它們之后刪除它們。另外,為了避免雙重丟棄,您需要在找到匹配項(xiàng)時(shí)中斷并繼續(xù)過去已標(biāo)記為丟棄的內(nèi)容。
import pandas as pd
test = pd.DataFrame(data = [3, 2, -4, 2, -3, 3, 2, 6, 7, 5, -6, 6, 3, 3, 4, 4], columns = ['Test'])
dropped = []
for idx1, i in enumerate(test['Test']):
if idx1 in dropped:
continue
for idx2, j in enumerate(test['Test']):
if idx2 in dropped or idx1 == idx2:
continue
if (i + j == 0):
dropped += [idx1,idx2]
break
for k in dropped:
test.drop(index = k, inplace = True)
print(test)
添加回答
舉報(bào)