2016-09-19 2 views
1

이것은 매우 단순 해 보이지만 내 머리카락을 당길 수 없다고 생각합니다.멀티 색인으로 팬다 피벗 테이블에 새 열 만들기

df['profit_loss'] = df['income'] - df['expenses] 

I에만 얻을 오류 : 나는 뭔가 같은 것이라고 생각 - (비용 수익) 나는이

 
Name  income   expenses 
     2015 2016  2015 2016 
Joe Doe  2  4   5  7 
Jane Doe 2  4   5  7 
Doe Joe  2  4   5  7 
Doe Jane 2  4   5  7 

같은 pivot_table가 단순히 계산 된 열 profit_loss =를 추가 할 수 있습니다.

이 pivot_table을 만드는 기본 테이블에 많은 코드 또는 준비 작업을 수행 할 필요없이 팬더 pivot_table에서 MultiIndexes을 처리하는 더 쉬운 방법이 있습니까?

+0

할 수 있습니다 [포스트] (http://stackoverflow.com/posts/39581185/edit)'df.to_dict()'의 출력을 사용하면 멀티 인덱스 DF를보다 쉽게 ​​만들 수 있습니까? – MaxU

답변

0

오류 때문에이 먼저 sort_index 사용할 수 있습니다

KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (0)'

그런 다음 원래 dfslicers 마지막 concata를 사용

df.sort_index(axis=1, inplace=True) 

idx = pd.IndexSlice 
a = df.loc[:,idx['income',:]] - df.loc[:,idx['expenses',:]].values 
#rename column name 
a = a.rename(columns={'income':'profit_loss'}) 
print (a) 
     profit_loss  
       2015 2016 
Joe Doe   -3 -3 
Jane Doe   -3 -3 
Doe Joe   -3 -3 
Doe Jane   -3 -3 

df1 = pd.concat([df,a], axis=1) 
print (df1) 
     expenses  income  profit_loss  
      2015 2016 2015 2016  2015 2016 
Joe Doe   5 7  2 4   -3 -3 
Jane Doe  5 7  2 4   -3 -3 
Doe Joe   5 7  2 4   -3 -3 
Doe Jane  5 7  2 4   -3 -3 
+0

내 대답이 도움이 되었다면 [수락] (http://meta.stackexchange.com/a/5235/295067)을 잊지 마세요. 감사. – jezrael

관련 문제