Pandas pivot_table using a given list of indices and columns
Question: I would like some help to figure out how to pivot a pandas dataframe into a
table with a given list of indices and columns (instead of the default
behavior where the indices and columns are picked automatically by pandas).
Apologies if this is trivial. I am new to python/pandas.

Consider the following dataframe:

    
    
    import pandas
    import numpy as np
    import datetime
    data = {
    'ticker' : np.array(['AAPL', 
                   'AAPL',
                   'IBM', 
                   'XOM']), 
                  'trade_date' : np.array([datetime.datetime(2015,01,01), 
                                        datetime.datetime(2015,04,02),
                                        datetime.datetime(2099,01,01), 
                                        datetime.datetime(2015,03,01)]), 
                 'price' : np.array([10.0, 15.6, 20.9, 13.5])
      }
    x = pandas.DataFrame(data)
    

Upon pivot_table,

    
    
    x.pivot_table(values = "price", index = "trade_date", columns = "ticker")
    

the result is:

    
    
    ticker      AAPL   IBM   XOM
    trade_date                  
    2015-01-01  10.0   NaN   NaN
    2015-03-01   NaN   NaN  13.5
    2015-04-02  15.6   NaN   NaN
    2099-01-01   NaN  20.9   NaN
    

However, what I want is:

    
    
    ticker      A    AA  AAPL   IBM   XOM
    trade_date                  
    2015-01-01  NaN  NaN 10.0   NaN   NaN
    2015-01-02  NaN  NaN NaN    NaN   NaN
    2015-03-01  NaN  NaN NaN   NaN  13.5
    2015-04-02  NaN  NaN 15.6   NaN   NaN
    2099-01-01  NaN  NaN NaN  20.9   NaN
    

There does not seem to be any provisions in pivot_table() to force a set of
indices and columns.

Is there a fast way of doing this? The data sets are fairly large, and it
would help to do this fast.


Answer: I'd reindex _after_ pivoting:

    
    
    In [11]: df = x.pivot_table(values = "price", index = "trade_date", columns = "ticker")
    
    In [12]: df
    Out[12]:
    ticker      AAPL   IBM   XOM
    trade_date
    2015-01-01  10.0   NaN   NaN
    2015-03-01   NaN   NaN  13.5
    2015-04-02  15.6   NaN   NaN
    2099-01-01   NaN  20.9   NaN
    
    In [13]: df.reindex_axis(["A", "AA", "AAPL", "IBM", "XOM"], axis=1)
    Out[13]:
    ticker       A  AA  AAPL   IBM   XOM
    trade_date
    2015-01-01 NaN NaN  10.0   NaN   NaN
    2015-03-01 NaN NaN   NaN   NaN  13.5
    2015-04-02 NaN NaN  15.6   NaN   NaN
    2099-01-01 NaN NaN   NaN  20.9   NaN
    

