我需要的细胞排除求和时,顶级的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
1条答案
按热度按时间lstz6jyr1#
屏蔽index与列标签相同的值,然后沿着
axis=1
计算sum