我正在尝试计算带有边距的简单数据透视表。在margins = False的情况下可以正常工作,但是当我尝试将margins设置为true时,我会得到一个Key Error。我该如何解决?
代码:
sp_outlook_distr.pivot_table(index=["Type"],
columns=sp_outlook_distr["Date"].dt.year, aggfunc={"Date": np.count_nonzero},
fill_value=0, margins=True)
错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-87-fdd674d20a28> in <module>()
1 # Distribution table - Outlook
----> 2 sp_outlook_distr.pivot_table(index=["Type"], columns=sp_outlook_distr["Date"].dt.year, aggfunc={"Date": np.count_nonzero}, fill_value=0, margins=True)
~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in pivot_table(self, values, index, columns, aggfunc, fill_value, margins, dropna, margins_name)
5298 aggfunc=aggfunc, fill_value=fill_value,
5299 margins=margins, dropna=dropna,
-> 5300 margins_name=margins_name)
5301
5302 def stack(self, level=-1, dropna=True):
~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/pivot.py in pivot_table(data, values, index, columns, aggfunc, fill_value, margins, dropna, margins_name)
122 cols=columns, aggfunc=aggfunc,
123 observed=dropna,
--> 124 margins_name=margins_name, fill_value=fill_value)
125
126 # discard the top level
~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/pivot.py in _add_margins(table, data, values, rows, cols, aggfunc, observed, margins_name, fill_value)
149 raise ValueError(msg)
150
--> 151 grand_margin = _compute_grand_margin(data, values, aggfunc, margins_name)
152
153 # could be passed a Series object with no 'columns'
~/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/pivot.py in _compute_grand_margin(data, values, aggfunc, margins_name)
219 grand_margin[k] = getattr(v, aggfunc)()
220 elif isinstance(aggfunc, dict):
--> 221 if isinstance(aggfunc[k], compat.string_types):
222 grand_margin[k] = getattr(v, aggfunc[k])()
223 else:
KeyError: 'Sovereign'
答案 0 :(得分:0)
尝试在数据透视表中使用values参数:
sp_outlook_distr.pivot_table(
index=["Type"],
columns=sp_outlook_distr["Date"].dt.year,
values=["Date"],
aggfunc={"Date": np.count_nonzero},
fill_value=0,
margins=True)