对不在列表中的列进行分组和求和

我有一个df数据框,其列具有以下模式:#number - letter并且我想添加一个新列other,该列对不在letter_table1and中的列求和letter_table2:


TEXT, A, B, C, D, E, F, G, H, I

a,1,1,1,2,2,2,3,3,3

b,1,1,1,2,2,2,3,3,3

c,1,1,1,2,2,2,3,3,3

d,1,1,1,2,2,2,3,3,3

e,1,1,1,2,2,2,3,3,3

f,1,1,1,2,2,2,3,3,3

g,1,1,1,2,2,2,3,3,3

h,1,1,1,2,2,2,3,3,3

i,1,1,1,2,2,2,3,3,3

j,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)



鸿蒙传说
浏览 151回答 1
1回答

largeQ

与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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python