2016-09-19 159 views
1

这看起来很简单,我简直不敢相信我在拉我的头发。 我有这样使用multiindex在pandas pivot_table上创建一个新列

 
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 =(收入 - 支出) 我认为这将是这样的:

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

我只得到错误。

无需为创建此pivot_table的基表编写大量代码或准备,是否有更简单的方法来处理pandas 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)'

然后使用slicers和最后concata原始df

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

相关问题