我是 Python/VBA 之旅的初學者,所以我有一個問題想問你。
所以我有一個 Excel 電子表格中的行串列(我也用 Pandas 處理這些資料以減少我必須在 Excel 上分析的行數)
事實是,我有成千上萬行在特定列中具有以下值:
col
0 -142.60
1 142.60
2 -565.78
3 565.78
4 -90.00
5 90.00
6 63.26
7 -63.26
8 117.96
所以我只想知道如何自動洗掉具有相應負數且總和 = 0 的行。
我只想要 117,96 行。
uj5u.com熱心網友回復:
假設您在此列中有浮點數,您可以將行與下一行的相反行進行比較,并使用此資訊僅對這些行進行子集化。
# is the next row the opposite value?
m = df['col'].eq(-df['col'].shift())
# drop the matching rows and the next ones
df2 = df.loc[~(m|m.shift(-1))]
輸出:
col
8 117.96
使用的輸入:
col
0 -142.60
1 142.60
2 -565.78
3 565.78
4 -90.00
5 90.00
6 63.26
7 -63.26
8 117.96
uj5u.com熱心網友回復:
從背景關系中不清楚“對應的負數”是否一定與實際數字相鄰。如果負數可能不在正數旁邊,而只是在陣列中的某個位置,我們可以執行以下操作。這里,df是從 Excel 資料構建的資料框。
# builds the same table with an additional column '_merge'.
# '_merge' column will be 'left_only' for rows whose negative
# does not appear and 'both' otherwise
df_all = df.merge(-df, how='left', indicator=True)
# selects rows with 'left_only' label
df = df.loc[df_all['_merge']=='left_only']
輸入:
0
0 -63.26
1 117.96
2 -565.78
3 63.26
4 142.60
5 565.78
6 90.00
7 -90.00
8 -142.60
輸出:
0
1 117.96
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/407228.html
標籤:
