简体   繁体   English

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

[英]Group and sum the columns that are not in the lists

I have a df data frame with columns with the following pattern: #number - letter and I want to add in a new column other that makes the sum of the columns that are not in letter_table1 and letter_table2 :我有一个df数据框,其列具有以下模式: #number - letter ,我想在一个新列中添加other列,使不在letter_table1letter_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

for instance:例如:

tableau_lettres1 = [H]
tableau_lettres2 = [I, J]

How can I do that?我怎样才能做到这一点? For the moment I have tried:目前我尝试过:

        df_sum['others'] = df.loc[:,~df.isin(tableau_lettres1, tableau_lettres2)].sum(axis=1)

as well as:也:

        df_sum['others'] = df.loc[:,df.drop(tableau_lettres1, tableau_lettres2)].sum(axis=1)

As tableau_lettres1, tableau_lettres2 are lists, you need to join them to one list, and get the other column names like:由于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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM