Pandas long to wide without losing timezone awareness
<p>I'm trying to reshape a pandas dataframe from long to wide format and the timestamps lose the timezone.</p>

<p>Here is a reproducible example:</p>

<pre><code>import pandas as pd
long = pd.DataFrame(dict(
    ind=[1,1,2, 2],
    events=['event1', 'event2', 'event1', 'event2'],
    time=[pd.Timestamp('2015-03-30 00:00:00', tz='UTC'),
         pd.Timestamp('2015-03-30 01:00:00', tz='UTC'),
         pd.Timestamp('2015-03-30 02:00:00', tz='UTC'),
         pd.Timestamp('2015-03-30 03:00:00', tz='UTC')]))
</code></pre>

<p>Then when looking at <code>long.time</code> I get a timezone-aware serie.</p>

<pre><code>0   2015-03-30 00:00:00+00:00
1   2015-03-30 01:00:00+00:00
2   2015-03-30 02:00:00+00:00
3   2015-03-30 03:00:00+00:00
Name: time, dtype: datetime64[ns, UTC]
</code></pre>

<p>and after reshaping like this</p>

<pre><code>wide = long.set_index(['ind'] + ['events']).unstack(level=1).reset_index()
</code></pre>

<p>the timezone goes away. E.g. <code>wide.time.event1</code></p>

<pre><code>0   2015-03-30 00:00:00
1   2015-03-30 02:00:00
Name: event1, dtype: datetime64[ns]
</code></pre>

<p>Is there another way of reshaping that does not lose the timezone?</p>

<p><code>pandas</code> is tracking the timezone.  When, you <code>unstack</code>, that reshaping must be happening in <code>numpy</code> which loses track.  This is proven by</p>

<pre><code>df = pd.concat([long.time, pd.Series(long.time.values)],
               axis=1, keys=['pandas', 'numpy'])

df
</code></pre>

<p><a href="http://i.stack.imgur.com/FeBkH.png" rel="nofollow"><img src="http://i.stack.imgur.com/FeBkH.png" alt="enter image description here"></a></p>

<pre><code>df.dtypes    

pandas    datetime64[ns, UTC]
numpy          datetime64[ns]
dtype: object
</code></pre>

<hr>

<p>Work around is to recast each column as the dtype you care about</p>

<pre><code>for c, col in wide.filter(like='time').iteritems():
    wide[c] = col.astype(long.time.dtype)

wide
</code></pre>

<p><a href="http://i.stack.imgur.com/m079M.png" rel="nofollow"><img src="http://i.stack.imgur.com/m079M.png" alt="enter image description here"></a></p>

python pandas timezone reshape