Repository: pandas-dev/pandas

Issue:
Inconsistent behavior when setting DataFrame index to datetime Series
Starting with a DataFrame like this:

```
df = pandas.DataFrame([{'ts':datetime(2014, 4, 1, tzinfo=pytz.utc), 'foo':1}])
```

This works fine:

```
df = df.set_index('ts')
print(df)
```

```
                           foo
ts                            
2014-04-01 00:00:00+00:00    1
```

This yields an AttributeError:

```
df.index = df['ts']
print(df)
```

```
In [75]: print(df)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-75-1152f648e0af> in <module>()
----> 1 print(df)

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/base.pyc in __str__(self)
     33         if compat.PY3:
     34             return self.__unicode__()
---> 35         return self.__bytes__()
     36 
     37     def __bytes__(self):

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/base.pyc in __bytes__(self)
     45 
     46         encoding = get_option("display.encoding")
---> 47         return self.__unicode__().encode(encoding, 'replace')
     48 
     49     def __repr__(self):

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/frame.pyc in __unicode__(self)
    458             width = None
    459         self.to_string(buf=buf, max_rows=max_rows, max_cols=max_cols,
--> 460                        line_width=width, show_dimensions=show_dimensions)
    461 
    462         return buf.getvalue()

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/frame.pyc in to_string(self, buf, columns, col_space, colSpace, header, index, na_rep, formatters, float_format, sparsify, nanRep, index_names, justify, force_unicode, line_width, max_rows, max_cols, show_dimensions)
   1297                                            max_cols=max_cols,
   1298                                            show_dimensions=show_dimensions)
-> 1299         formatter.to_string()
   1300 
   1301         if buf is None:

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/format.pyc in to_string(self, force_unicode)
    378             text = info_line
    379         else:
--> 380             strcols = self._to_str_columns()
    381             if self.line_width is None:
    382                 text = adjoin(1, *strcols)

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/format.pyc in _to_str_columns(self)
    310 
    311         # may include levels names also
--> 312         str_index = self._get_formatted_index()
    313         str_columns = self._get_formatted_column_labels()
    314 

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/format.pyc in _get_formatted_index(self)
    583                                      formatter=fmt)
    584         else:
--> 585             fmt_index = [index.format(name=show_index_names, formatter=fmt)]
    586 
    587         adjoined = adjoin(1, *fmt_index).split('\n')

/home/sucram/.virtualenvs/ehubdata/local/lib/python2.7/site-packages/pandas/core/generic.pyc in __getattr__(self, name)
   1813                 return self[name]
   1814             raise AttributeError("'%s' object has no attribute '%s'" %
-> 1815                                  (type(self).__name__, name))
   1816 
   1817     def __setattr__(self, name, value):

AttributeError: 'Series' object has no attribute 'format'
```



Discussion:
can you show version of pandas/numpy

Right, sorry:

numpy==1.8.1
pandas==0.13.1

```
In [15]: df.index = df['ts']

In [16]: df
Out[16]: 
            foo                         ts
ts                                        
2014-04-01    1  2014-04-01 00:00:00+00:00

[1 rows x 2 columns]

In [17]: df.index
Out[17]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-04-01]
Length: 1, Freq: None, Timezone: None
```

This works in master, except that it drops the tz (easy to fix though,
their is now a way to keep/discard the tz when creating a series `keep_tz`)


Resolving patch:
diff --git a/pandas/core/index.py b/pandas/core/index.py
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -154,7 +154,7 @@ def __new__(cls, data, dtype=None, copy=False, name=None, fastpath=False,
                 if (inferred.startswith('datetime') or
                         tslib.is_timestamp_array(subarr)):
                     from pandas.tseries.index import DatetimeIndex
-                    return DatetimeIndex(data, copy=copy, name=name, **kwargs)
+                    return DatetimeIndex(subarr, copy=copy, name=name, **kwargs)
                 elif inferred == 'period':
                     return PeriodIndex(subarr, name=name, **kwargs)
 


Test patch:
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -2125,6 +2125,15 @@ def test_set_index_cast_datetimeindex(self):
         result = df['D']
         assert_series_equal(result, expected)
 
+        # GH 6785
+        # set the index manually
+        import pytz
+        df = DataFrame([{'ts':datetime(2014, 4, 1, tzinfo=pytz.utc), 'foo':1}])
+        expected = df.set_index('ts')
+        df.index = df['ts']
+        df.pop('ts')
+        assert_frame_equal(df, expected)
+
     def test_set_index_multiindexcolumns(self):
         columns = MultiIndex.from_tuples([('foo', 1), ('foo', 2), ('bar', 1)])
         df = DataFrame(np.random.randn(3, 3), columns=columns)