来自Pivot元组索引的MultiIndex

时间:2017-03-10 19:21:54

标签: python pandas pivot-table

我有一个我从数据框创建的数据透视表,索引是一个元组(["Warehouse", "Month"]),但是当我运行时:

multi.index = pd.MultiIndex.from_tuples(pivoted.index)

我收到以下错误:

TypeError: Expected tuple, got str

下面的完整代码:

hedrows = cursor.fetchall()
for row in hedrows :
    total_issues = total_issues + 1
issue_df = pd.read_sql(issue_query, cnxn)
issue_df.rename(columns={'00001' : 'Invoices', 'OBWHID' : 'Warehouse', 'OBRTRC':'Reason', 'INV_MONTH':'Month', '00005':'Date'}, inplace=True)
pivoted = pd.pivot_table(issue_df, index=["Warehouse", "Month"], values=["Invoices"], columns=['Reason'], aggfunc='count', fill_value=0)
warehouse_percentages=pivoted
total_percentages=pivoted
warehouse_percentages=pivoted
total_percentages=pivoted
#Percentages of Warehouse Returns by Month
warehouse_percentages =  100 * warehouse_percentages[:].div(warehouse_percentages[:].sum(axis=1), axis=0)
pivoted.loc['Column Total'] = pivoted.sum()
#Percentages of Total Returns by Month
total_percentages = total_percentages.div(total_issues)
multi.index = pd.MultiIndex.from_tuples(pivoted.index)

1 个答案:

答案 0 :(得分:0)

设置

pivoted.loc['Column Total'] = pivoted.sum()

你的DataFrame来自像

这样的MultiIndex
In [1]: pivoted
                 CE  CS  DG  DR  IC  IO
Warehouse Month                        
01        01      9   4   6   5   6   6
02        02      5   3   2   1   3   1

In [2]: pivoted.index
Out[2]: 
MultiIndex(levels=[['01', '02'], ['01', '02']],
           labels=[[0, 1], [0, 1]],
           names=['Warehouse', 'Month'])

索引dtype='object'由前一个索引中的元组和新的'Column Total'字符串组成。

In [3]: pivoted.loc['Column Total'] = pivoted.sum()

In [4]: pivoted
Out[4]: 
              CE  CS  DG  DR  IC  IO
(01, 01)       9   4   6   5   6   6
(02, 02)       5   3   2   1   3   1
Column Total  14   7   8   6   9   7

In [5]: pivoted.index
Out[5]: Index([('01', '01'), ('02', '02'), 'Column Total'], dtype='object')

现在因为'Column Total'显然是一个字符串而不是一个元组,所以应该清楚为什么会出现这个错误 - from_tuples需要一个元组列表,而不是元组列表和一个字符串。

我不完全确定你想要的行为在这里或你在做什么,但我建议在你的MultiIndex中添加列总和作为一行,除非你有一个很有道理的。如果您需要某些聚合的总和,您可以随时计算它们,或将它们存储在单独的系列中。

在任何情况下,您都可以添加一个总行(当然,只要您操作DataFrame就会失效)并保留您的MultiIndex,例如

In [6]: df.loc[('Total', 'Total'), :] = df.sum()

In [7]: df
Out[7]: 
                   CE   CS   DG   DR   IC   IO
Warehouse Month                               
01        01      9.0  4.0  6.0  5.0  6.0  6.0
02        02      5.0  3.0  2.0  1.0  3.0  1.0
Total     Total  14.0  7.0  8.0  6.0  9.0  7.0
相关问题