Convert table using python pandas
Question: I have a table like this:

    
    
    vstid vstrseq  date       page   timespent
    1       1     1/1/16      a       20.00
    1       1     1/1/16      b       3.00
    1       1     1/1/16      c       131.00
    1       1     1/1/16      d        .000
    1       1     1/1/16      a       3.00
    

I want this like:

    
    
    A      B             date                  a      b      c       d
    1      1             1/1/16                23     3      131     0
    

How can I get it done in python? Any suggestions?


Answer: You could use pandas' [`pivot table`](http://pandas.pydata.org/pandas-
docs/stable/generated/pandas.pivot_table.html) for this:

    
    
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({
        "vstid": [1]*5,
        "vstrseq": [1]*5,
        "date": ["1/1/16"]*5,
        "page": ["a", "b", "c", "d", "a"],
        "timespent": [20.00, 3.00, 131.00, 0.000, 3.00]
        })
    
    table = df.pivot_table(index=["vstid", "vstrseq", "date"], values="timespent", columns="page", aggfunc=np.sum).reset_index()
    
    print table.to_string(index=False)
    

which outputs

    
    
     vstid  vstrseq    date   a  b    c  d
         1        1  1/1/16  23  3  131  0 
    

