Skip to content

Commit ff4df5a

Browse files
committed
ERR: raise on missing values in pd.pivot_table #14938
1 parent 8b497e4 commit ff4df5a

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

doc/source/whatsnew/v0.20.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -300,3 +300,4 @@ Bug Fixes
300300
- Bug in ``Series.unique()`` in which unsigned 64-bit integers were causing overflow (:issue:`14721`)
301301
- Require at least 0.23 version of cython to avoid problems with character encodings (:issue:`14699`)
302302
- Bug in converting object elements of array-like objects to unsigned 64-bit integers (:issue:`4471`)
303+
- Bug in ``pd.pivot_table()`` where no error was raised when values argument was not in the columns (:issue:`14938`)

pandas/tests/groupby/test_groupby.py

+14
Original file line numberDiff line numberDiff line change
@@ -5725,6 +5725,20 @@ def test_group_shift_with_null_key(self):
57255725

57265726
assert_frame_equal(result, expected)
57275727

5728+
def test_pivot_table_values_key_error(self):
5729+
# This test is designed to replicate the error in issue #14938
5730+
df = pd.DataFrame({'eventDate':
5731+
pd.date_range(pd.datetime.today(),
5732+
periods=20, freq='M').tolist(),
5733+
'thename': range(0, 20)})
5734+
5735+
df['year'] = df.set_index('eventDate').index.year
5736+
df['month'] = df.set_index('eventDate').index.month
5737+
5738+
with self.assertRaises(KeyError):
5739+
df.reset_index().pivot_table(index='year', columns='month',
5740+
values='badname', aggfunc='count')
5741+
57285742
def test_agg_over_numpy_arrays(self):
57295743
# GH 3788
57305744
df = pd.DataFrame([[1, np.array([10, 20, 30])],

pandas/tools/pivot.py

+5
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
107107
values_multi = False
108108
values = [values]
109109

110+
# GH14938 Make sure value labels are in data
111+
for i in values:
112+
if i not in data:
113+
raise KeyError(i)
114+
110115
to_filter = []
111116
for x in keys + values:
112117
if isinstance(x, Grouper):

0 commit comments

Comments
 (0)