如果列名和行名相似,则multiindex列和行匹配,并排除在那些单元格python pandas中添加的值

pinkon5k  于 2023-06-20  发布在  Python
关注(0)|答案(1)|浏览(92)

我需要的细胞排除求和时,顶级的multiindex(国家1和国家2)是相同的行和列

import pandas as pd
label_columns1 = ['Country1','Country2']
label_columns2 = ['agri1', 'agri2']
label_rows1 = ['Country1','Country2']
label_rows2 = ['agri1', 'agri2']

df = pd.DataFrame([[1,2,3,4]], index=pd.MultiIndex.from_product([label_rows1,label_rows2]), 
                     columns=pd.MultiIndex.from_product([label_columns1, label_columns2 ]))
df
                     Country1     Country2
                   agri1  agri2   agri1  agri2  
Country1    agri1   1      2      3       4
            agri2   1      2      3       4
Country2    agri1   1      2      3       4
            agri2   1      2      3       4

我知道这将给我行求和和一个新列

df[('Total',"Vlaue")] = df.sum(axis=1)

df

Country1     Country2  Total
                   agri1  agri2   agri1  agri2 Value    
Country1    agri1   1      2      3       4     10
            agri2   1      2      3       4     10
Country2    agri1   1      2      3       4     10
            agri2   1      2      3       4     10

我真正想要的,也是一直在努力的,只是在列和行索引不相同的情况下添加单元格。在这种情况下,例如第一行将是7。我的数据框很大,行和列太多。到目前为止我所尝试的

for col in df.columns:
    for row in df.index:
        if col != row:
            df[('Total',"Vlaue")] = df.sum(axis=1)

这给了我意想不到的结果,但我想我已经接近了。我的预期结果应该如下所示

Country1     Country2      Total
                   agri1  agri2   agri1  agri2  Value   
Country1    agri1   1      2      3       4     (3+4) = 7
            agri2   1      2      3       4     (3+4) = 7
Country2    agri1   1      2      3       4     (1+2) = 3
            agri2   1      2      3       4     (1+2) = 3
lstz6jyr

lstz6jyr1#

屏蔽index与列标签相同的值,然后沿着axis=1计算sum

ix = df.index.get_level_values(0)
cx = df.columns.get_level_values(0)

m = ix.values[:, None] == cx.values
df[('Total', 'Value')] = df.mask(m).sum(axis=1)
Country1       Country2       Total
                  agri1 agri2    agri1 agri2 Value
Country1 agri1        1     2        3     4   7.0
         agri2        1     2        3     4   7.0
Country2 agri1        1     2        3     4   3.0
         agri2        1     2        3     4   3.0

相关问题