문제 설명
다단계 열 테이블에 부분합 열 추가 (Adding a subtotal column to a multilevel column table)
피벗 후 내 데이터 프레임입니다.
Country London Shanghai
PriceRange 100‑200 200‑300 300‑400 100‑200 200‑300 300‑400
Code
A 1 1 1 2 2 2
B 10 10 10 20 20 20
다음을 달성하기 위해 모든 국가 뒤에 열을 추가할 수 있습니까?
Country London Shanghai All
PriceRange 100‑200 200‑300 300‑400 SubTotal 100‑200 200‑300 300‑400 SubTotal 100‑200 200‑300 300‑400 SubTotal
Code
A 1 1 1 3 2 2 2 6 3 3 3 9
B 10 10 10 30 20 20 20 60 30 30 30 90
하지만 margins=True를 사용할 수 있다는 것을 알고 있습니다. 그것은 단지 최종 총계를 추가합니다. 이를 달성하기 위해 사용할 수 있는 옵션이 있습니까? 감사합니다.
참조 솔루션
방법 1:
Let us using sum
with join
s=df.sum(level=0,axis=1)
s.columns=pd.MultiIndex.from_product([list(s),['subgroup']])
df=df.join(s).sort_index(level=0,axis=1).assign(Group=df.sum(axis=1))
df
A B Group
1 2 3 subgroup 1 2 3 subgroup
Code
A 1 1 1 3 2 2 2 6 9
B 10 10 10 30 20 20 20 60 90