我有一個龐大的數據庫,其中有一些預算轉移,當查看總計時,它們會相互抵消。問題是,我似乎無法理解如何刪除所有相互抵消的行。下面的數據框作為示例:test = pd.DataFrame(data = [1050.77, 13.45, 6.26, -1050.77, 10027, 6.26, 13.45, 13.45, -13.45, -6.26, -16800, 16800], columns = ['Test']) Test0 1050.771 13.452 6.263 -1050.774 100275 6.266 13.457 13.458 -13.459 -6.2610 -1680011 16800上面的總和是 10060.16如您所見,以下數字相互抵消:0 1050.773 -1050.771 13.458 -13.452 6.269 -6.2610 -1680011 16800因此,期望的輸出是: Test4 100275 6.266 13.457 13.45當然,上面的總和是 10060.16。我已經嘗試了很多東西,但我無法讓它工作。下面的代碼是我所做的嘗試之一,但它不起作用:for idx1, i in enumerate(test['Test']): for idx2, j in enumerate(test['Test']): if (i + j == 0): test.drop(index = idx1, inplace = True) test.drop(index = idx2, inplace = True) test我可以刪除取消另一個的號碼,然后使用 dropna 消除空行,或者最好的結果是刪除該號碼具有“取消器”的整行我不關心索引,它可以以任何方式更改。目標是僅消除 + 和 - 數字的完美匹配。編輯:我已經編輯了 DataFrame,所以它帶有一些浮點數任何有關如何編程的幫助將不勝感激。
1 回答

達令說
TA貢獻1821條經驗 獲得超6個贊
您應該避免在迭代列表時修改列表。而是創建一個索引列表以刪除它們,然后在您找到它們之后刪除它們。另外,為了避免雙重丟棄,您需要在找到匹配項時中斷并繼續過去已標記為丟棄的內容。
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)
添加回答
舉報
0/150
提交
取消