分组和汇总不在列表中的列

时间:2019-10-15 08:21:08

标签: python python-3.x dataframe sum

我有一个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

例如:

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 个答案:

答案 0 :(得分:0)

由于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)