DatetimeIndex columns cause reset_index() to throw AttributeError · Issue #5818 · pandas-dev/pandas (original) (raw)
It appears that if a dataframe has column headers of type DatetimeIndex, calling reset_index() throws AttributeError: 'str' object has no attribute 'view'
. I see this both in v0.12 and the master branch.
If column headers are strings or integers, reset_index() works fine.
I'm guessing it's treating the new column array as type DatetimeIndex whereas it now has a string in the 0th position ('index'). Maybe the reset_index should first cast the columns as object and convert the DatetimeIndex values to strings?
In [48]: df = pd.DataFrame(data=np.random.rand(2, 2), columns=pd.date_range('1/1/2013', '1/2/2013'), index=['A', 'B'])
In [49]: df.reset_index()
AttributeError Traceback (most recent call last) in () ----> 1 df.reset_index()
/home/user/environments/python3/src/pandas/pandas/core/frame.py in reset_index(self, level, drop, inplace, col_level, col_fill) 2447 else: 2448 values = _maybe_cast(self.index.values) -> 2449 new_obj.insert(0, name, values) 2450 2451 new_obj.index = new_index
/home/user/environments/python3/src/pandas/pandas/core/frame.py in insert(self, loc, column, value, allow_duplicates) 1940 value = self._sanitize_column(column, value) 1941 self._data.insert( -> 1942 loc, column, value, allow_duplicates=allow_duplicates) 1943 1944 def _sanitize_column(self, key, value):
/home/user/environments/python3/src/pandas/pandas/core/internals.py in insert(self, loc, item, value, allow_duplicates) 2899 2900 try: -> 2901 new_items = self.items.insert(loc, item) 2902 self.set_items_norename(new_items) 2903
/home/user/environments/python3/src/pandas/pandas/tseries/index.py in insert(self, loc, item) 1539 1540 new_index = np.concatenate((self[:loc].asi8, -> 1541 [item.view(np.int64)], 1542 self[loc:].asi8)) 1543 return DatetimeIndex(new_index, freq='infer')
AttributeError: 'str' object has no attribute 'view'
In [50]: df = pd.DataFrame(data=np.random.rand(2, 2), columns=[1, 2], index=['A', 'B']) In [51]: df.reset_index() Out[51]: index 1 2 0 A 0.947575 0.370406 1 B 0.664856 0.686524
[2 rows x 3 columns]
In [52]: df = pd.DataFrame(data=np.random.rand(2, 2), columns=['C', 'D'], index=['A', 'B'])
In [53]: df.reset_index() Out[53]: index C D 0 A 0.053455 0.599483 1 B 0.776364 0.680425
[2 rows x 3 columns]