我有一個df數據框,其列具有以下模式:#number - letter并且我想添加一個新列other,該列對不在letter_table1and中的列求和letter_table2:TEXT, A, B, C, D, E, F, G, H, Ia,1,1,1,2,2,2,3,3,3b,1,1,1,2,2,2,3,3,3c,1,1,1,2,2,2,3,3,3d,1,1,1,2,2,2,3,3,3e,1,1,1,2,2,2,3,3,3f,1,1,1,2,2,2,3,3,3g,1,1,1,2,2,2,3,3,3h,1,1,1,2,2,2,3,3,3i,1,1,1,2,2,2,3,3,3j,1,1,1,2,2,2,3,3,3例如 :tableau_lettres1 = [H]tableau_lettres2 = [I, J]我怎樣才能做到這一點?目前我嘗試過: df_sum['others'] = df.loc[:,~df.isin(tableau_lettres1, tableau_lettres2)].sum(axis=1)也: df_sum['others'] = df.loc[:,df.drop(tableau_lettres1, tableau_lettres2)].sum(axis=1)
1 回答

largeQ
TA貢獻2039條經驗 獲得超8個贊
與tableau_lettres1, tableau_lettres2
列表一樣,您需要將它們加入一個列表,并獲取其他列名稱,例如:
df_sum['others'] = df[[col for col in df.columns.tolist() if col not in tableau_lettres1 + tableau_lettres2]].sum(axis=1)
添加回答
舉報
0/150
提交
取消