Create or modify DataFrame using another DataFrame
<p>I currently have a Pandas DataFrame looking like this:</p>

<pre><code>   DATESTAMP   price                name   pct_chg
0  2006-01-02  62.987301            a      0.000000
1  2006-01-03  61.990700            a     -0.015822
2  2006-01-04  62.987301            a      0.016077
3  2006-01-05  62.987301            a      0.000000
4  2006-01-06  61.990700            a     -0.015822
6  2006-01-04  100.1                b      0.000000
7  2006-01-05  100.5                b     -0.015822
8  2006-01-06  100.7                b      0.016077
9  2006-01-07  100.8                b      0.016090
</code></pre>

<p>The problem is that different items (specified with unique column <code>name</code>) have different time of origination as well as being alive for different amount of time</p>

<ul>
<li>Above item <code>a</code> starts at <code>2016-01-02</code> and ends at <code>2016-01-06</code></li>
<li>Above item <code>b</code> starts at <code>2006-01-04</code> and ends at <code>2006-01-07</code>.</li>
</ul>

<p>I would like to summarize the column <code>pct_chg</code> in a new DataFrame, having <code>DATESTAMP</code> as index and columns as of <code>name</code>. I would also like the new DataFrame to have the index in such a manner that it starts with the "oldest" existing date-record (in this case <code>2006-01-02</code>) and ends at the "newest" (in this case <code>2006-01-07</code>).</p>

<p>The result would look like</p>

<pre><code>            a          b
2006-01-02  0.000000   NaN
2006-01-03  -0.015822  NaN
2006-01-04  0.016077   0.000000
2006-01-05  0.000000   -0.015822
2006-01-06  -0.015822  0.016077
2006-01-07  NaN        0.016090
</code></pre>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a>:</p>

<pre><code>print (df.set_index(['DATESTAMP','name'])['pct_chg'].unstack())
name               a         b
DATESTAMP                     
2006-01-02  0.000000       NaN
2006-01-03 -0.015822       NaN
2006-01-04  0.016077  0.000000
2006-01-05  0.000000 -0.015822
2006-01-06 -0.015822  0.016077
2006-01-07       NaN  0.016090
</code></pre>

<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot.html" rel="nofollow"><code>pivot</code></a>:</p>

<pre><code>print (df.pivot(index='DATESTAMP', columns='name', values='pct_chg'))
name               a         b
DATESTAMP                     
2006-01-02  0.000000       NaN
2006-01-03 -0.015822       NaN
2006-01-04  0.016077  0.000000
2006-01-05  0.000000 -0.015822
2006-01-06 -0.015822  0.016077
2006-01-07       NaN  0.016090
</code></pre>

python pandas dataframe pivot reshape