I have a dataframe of Date, Buy, and Sell values and doing a pivot_table
on that dataframe to get all Buy/Sell value of each date which works.
data = [('20170325', 'Buy', 400 ),
('20170325', 'Buy', 401 ),
('20170323', 'Buy', 400 ),
('20170324', 'Sell', 400 )]
testDf = pd.DataFrame(data, columns=['Date', 'Scenario', 'Value'])
df1 = pd.pivot_table(testDf, columns='Scenario', index='Date', values='Value',
fill_value = '', aggfunc=lambda x: x.tolist() if len(x)>1 else x)
df1
# Scenario Buy Sell
# Date
# 20170323 400
# 20170324 400
# 20170325 [400, 401]
But when my data changes a bit, pivot_table
throws error: ValueError: Function does not reduce. Not able to understand why. Here is the error with different data. Please note that Date of 20170325 is changed to 20170321.
data = [('20170321', 'Buy', 400 ),
('20170321', 'Buy', 401 ),
('20170323', 'Buy', 400 ),
('20170324', 'Sell', 400 )]
testDf = pd.DataFrame(data, columns=['Date', 'Scenario', 'Value'])
df1 = pd.pivot_table(testDf, columns='Scenario', index='Date', values='Value',
fill_value = '',aggfunc=lambda x: x.tolist() if len(x)>1 else x)
Traceback (most recent call last): File "", line 1, in
File "ext2\vc12_win32\lib\python2.7\site-packages\pandas\tools\pivot.py", line 114, in pivot_table
File "ext2\vc12_win32\lib\python2.7\site-packages\pandas\core\groupby.py", line 729, in agg
File "ext2\vc12_win32\lib\python2.7\site-packages\pandas\core\groupby.py", line 2978, in aggregate
File "ext2\vc12_win32\lib\python2.7\site-packages\pandas\core\groupby.py", line 1227, in _python_agg_general
File "ext2\vc12_win32\lib\python2.7\site-packages\pandas\core\groupby.py", line 1733, in agg_series
File "ext2\vc12_win32\lib\python2.7\site-packages\pandas\core\groupby.py", line 1767, in _aggregate_series_pure_python
ValueError: Function does not reduce